file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/11155111/0x2d43c99479F4e5aE23fB930a3350D44b6a632CAa/sources/contracts/manifold/creator-core/core/ERC721CreatorCore.sol | Post-burning callback and metadata cleanup/ Callback to originating extension if needed Clear metadata (if any) | function _postBurn(
address owner,
uint256 tokenId,
address extension
) internal virtual {
if (extension != address(0)) {
if (
ERC165Checker.supportsInterface(
extension,
type(IERC721CreatorExtensionBurnable).interfaceId
)
) {
IERC721CreatorExtensionBurnable(extension).onBurn(
owner,
tokenId
);
}
}
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
| 3,836,250 |
./full_match/1/0x35B62Cb442A3b67082080a1e8F5c377811A45613/sources/browser/DPiggy.sol | Forwarding function to dPiggy asset to execute the Compound redeem. tokenAddresses Array with ERC20 token addresses or '0x0' for Ethereum. The asset must already exist on dPiggy./ | function executeCompoundRedeem(address[] calldata tokenAddresses) nonReentrant external {
_setAsset(tokenAddresses, abi.encodeWithSignature("executeCompoundRedeem()"));
}
| 8,369,364 |
//Address: 0x752673c6d104e045129247fbbd806dbbfdfa64da
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 5/27/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
/*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Standard ERC20 token
*
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, SafeMath {
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function transfer(address _to, uint _value) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Ownable
*
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
*/
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Moeda Loaylty Points token contract
contract MoedaToken is StandardToken, Ownable {
string public constant name = "Moeda Loyalty Points";
string public constant symbol = "MLO";
uint8 public constant decimals = 18;
// don't allow creation of more than this number of tokens
uint public constant MAX_TOKENS = 20000000 ether;
// transfers are locked during the sale
bool public saleActive;
// only emitted during the crowdsale
event Created(address indexed donor, uint256 tokensReceived);
// determine whether transfers can be made
modifier onlyAfterSale() {
if (saleActive) {
throw;
}
_;
}
modifier onlyDuringSale() {
if (!saleActive) {
throw;
}
_;
}
/// @dev Create moeda token and lock transfers
function MoedaToken() {
saleActive = true;
}
/// @dev unlock transfers
function unlock() onlyOwner {
saleActive = false;
}
/// @dev create tokens, only usable while saleActive
/// @param recipient address that will receive the created tokens
/// @param amount the number of tokens to create
function create(address recipient, uint256 amount)
onlyOwner onlyDuringSale {
if (amount == 0) throw;
if (safeAdd(totalSupply, amount) > MAX_TOKENS) throw;
balances[recipient] = safeAdd(balances[recipient], amount);
totalSupply = safeAdd(totalSupply, amount);
Created(recipient, amount);
}
// transfer tokens
// only allowed after sale has ended
function transfer(address _to, uint _value) onlyAfterSale returns (bool) {
return super.transfer(_to, _value);
}
// transfer tokens
// only allowed after sale has ended
function transferFrom(address from, address to, uint value) onlyAfterSale
returns (bool)
{
return super.transferFrom(from, to, value);
}
}
/// @title Moeda crowdsale
contract Crowdsale is Ownable, SafeMath {
bool public crowdsaleClosed; // whether the crowdsale has been closed
// manually
address public wallet; // recipient of all crowdsale funds
MoedaToken public moedaToken; // token that will be sold during sale
uint256 public etherReceived; // total ether received
uint256 public totalTokensSold; // number of tokens sold
uint256 public startBlock; // block where sale starts
uint256 public endBlock; // block where sale ends
// used to scale token amounts to 18 decimals
uint256 public constant TOKEN_MULTIPLIER = 10 ** 18;
// number of tokens allocated to presale (prior to crowdsale)
uint256 public constant PRESALE_TOKEN_ALLOCATION = 5000000 * TOKEN_MULTIPLIER;
// recipient of presale tokens
address public PRESALE_WALLET = "0x30B3C64d43e7A1E8965D934Fa96a3bFB33Eee0d2";
// smallest possible donation
uint256 public constant DUST_LIMIT = 1 finney;
// token generation rates (tokens per eth)
uint256 public constant TIER1_RATE = 160;
uint256 public constant TIER2_RATE = 125;
uint256 public constant TIER3_RATE = 80;
// limits for each pricing tier (how much can be bought)
uint256 public constant TIER1_CAP = 31250 ether;
uint256 public constant TIER2_CAP = 71250 ether;
uint256 public constant TIER3_CAP = 133750 ether; // Total ether cap
// Log a purchase
event Purchase(address indexed donor, uint256 amount, uint256 tokenAmount);
// Log transfer of tokens that were sent to this contract by mistake
event TokenDrain(address token, address to, uint256 amount);
modifier onlyDuringSale() {
if (crowdsaleClosed) {
throw;
}
if (block.number < startBlock) {
throw;
}
if (block.number >= endBlock) {
throw;
}
_;
}
/// @dev Initialize a new Crowdsale contract
/// @param _wallet address of multisig wallet that will store received ether
/// @param _startBlock block at which to start the sale
/// @param _endBlock block at which to end the sale
function Crowdsale(address _wallet, uint _startBlock, uint _endBlock) {
if (_wallet == address(0)) throw;
if (_startBlock <= block.number) throw;
if (_endBlock <= _startBlock) throw;
crowdsaleClosed = false;
wallet = _wallet;
moedaToken = new MoedaToken();
startBlock = _startBlock;
endBlock = _endBlock;
}
/// @dev Determine the lowest rate to acquire tokens given an amount of
/// donated ethers
/// @param totalReceived amount of ether that has been received
/// @return pair of the current tier's donation limit and a token creation rate
function getLimitAndPrice(uint256 totalReceived)
constant returns (uint256, uint256) {
uint256 limit = 0;
uint256 price = 0;
if (totalReceived < TIER1_CAP) {
limit = TIER1_CAP;
price = TIER1_RATE;
}
else if (totalReceived < TIER2_CAP) {
limit = TIER2_CAP;
price = TIER2_RATE;
}
else if (totalReceived < TIER3_CAP) {
limit = TIER3_CAP;
price = TIER3_RATE;
} else {
throw; // this shouldn't happen
}
return (limit, price);
}
/// @dev Determine how many tokens we can get from each pricing tier, in
/// case a donation's amount overlaps multiple pricing tiers.
///
/// @param totalReceived ether received by contract plus spent by this donation
/// @param requestedAmount total ether to spend on tokens in a donation
/// @return amount of tokens to get for the requested ether donation
function getTokenAmount(uint256 totalReceived, uint256 requestedAmount)
constant returns (uint256) {
// base case, we've spent the entire donation and can stop
if (requestedAmount == 0) return 0;
uint256 limit = 0;
uint256 price = 0;
// 1. Determine cheapest token price
(limit, price) = getLimitAndPrice(totalReceived);
// 2. Since there are multiple pricing levels based on how much has been
// received so far, we need to determine how much can be spent at
// any given tier. This in case a donation will overlap more than one
// tier
uint256 maxETHSpendableInTier = safeSub(limit, totalReceived);
uint256 amountToSpend = min256(maxETHSpendableInTier, requestedAmount);
// 3. Given a price determine how many tokens the unspent ether in this
// donation will get you
uint256 tokensToReceiveAtCurrentPrice = safeMul(amountToSpend, price);
// You've spent everything you could at this level, continue to the next
// one, in case there is some ETH left unspent in this donation.
uint256 additionalTokens = getTokenAmount(
safeAdd(totalReceived, amountToSpend),
safeSub(requestedAmount, amountToSpend));
return safeAdd(tokensToReceiveAtCurrentPrice, additionalTokens);
}
/// grant tokens to buyer when we receive ether
/// @dev buy tokens, only usable while crowdsale is active
function () payable onlyDuringSale {
if (msg.value < DUST_LIMIT) throw;
if (safeAdd(etherReceived, msg.value) > TIER3_CAP) throw;
uint256 tokenAmount = getTokenAmount(etherReceived, msg.value);
moedaToken.create(msg.sender, tokenAmount);
etherReceived = safeAdd(etherReceived, msg.value);
totalTokensSold = safeAdd(totalTokensSold, tokenAmount);
Purchase(msg.sender, msg.value, tokenAmount);
if (!wallet.send(msg.value)) throw;
}
/// @dev close the crowdsale manually and unlock the tokens
/// this will only be successful if not already executed,
/// if endBlock has been reached, or if the cap has been reached
function finalize() onlyOwner {
if (block.number < startBlock) throw;
if (crowdsaleClosed) throw;
// if amount remaining is too small we can allow sale to end earlier
uint256 amountRemaining = safeSub(TIER3_CAP, etherReceived);
if (block.number < endBlock && amountRemaining >= DUST_LIMIT) throw;
// create and assign presale tokens to presale wallet
moedaToken.create(PRESALE_WALLET, PRESALE_TOKEN_ALLOCATION);
// unlock tokens for spending
moedaToken.unlock();
crowdsaleClosed = true;
}
/// @dev Drain tokens that were sent here by mistake
/// because people will.
/// @param _token address of token to transfer
/// @param _to address where tokens will be transferred
function drainToken(address _token, address _to) onlyOwner {
if (_token == address(0)) throw;
if (_to == address(0)) throw;
ERC20 token = ERC20(_token);
uint256 balance = token.balanceOf(this);
token.transfer(_to, balance);
TokenDrain(_token, _to, balance);
}
}
| Determine how many tokens we can get from each pricing tier, in case a donation's amount overlaps multiple pricing tiers. totalReceived ether received by contract plus spent by this donation requestedAmount total ether to spend on tokens in a donation return amount of tokens to get for the requested ether donation base case, we've spent the entire donation and can stop 1. Determine cheapest token price 2. Since there are multiple pricing levels based on how much has been received so far, we need to determine how much can be spent at any given tier. This in case a donation will overlap more than one tier 3. Given a price determine how many tokens the unspent ether in this donation will get you You've spent everything you could at this level, continue to the next one, in case there is some ETH left unspent in this donation. | function getTokenAmount(uint256 totalReceived, uint256 requestedAmount)
constant returns (uint256) {
if (requestedAmount == 0) return 0;
uint256 limit = 0;
uint256 price = 0;
(limit, price) = getLimitAndPrice(totalReceived);
uint256 maxETHSpendableInTier = safeSub(limit, totalReceived);
uint256 amountToSpend = min256(maxETHSpendableInTier, requestedAmount);
uint256 tokensToReceiveAtCurrentPrice = safeMul(amountToSpend, price);
uint256 additionalTokens = getTokenAmount(
safeAdd(totalReceived, amountToSpend),
safeSub(requestedAmount, amountToSpend));
return safeAdd(tokensToReceiveAtCurrentPrice, additionalTokens);
}
| 12,701,805 |
./full_match/42220/0x3c6E9000c449D15E584Bc1aB98E9AA14a5fcce0F/sources/contracts/interfaces/IElection.sol | only owner only VM view functions | interface IElection {
function vote(
address,
uint256,
address,
address
) external returns (bool);
function activate(address) external returns (bool);
function activateForAccount(address, address) external returns (bool);
function revokeActive(
address,
uint256,
address,
address,
uint256
) external returns (bool);
function revokeAllActive(
address,
address,
address,
uint256
) external returns (bool);
function revokePending(
address,
uint256,
address,
address,
uint256
) external returns (bool);
function markGroupIneligible(address) external;
function markGroupEligible(
address,
address,
address
) external;
function forceDecrementVotes(
address,
uint256,
address[] calldata,
address[] calldata,
uint256[] calldata
) external returns (uint256);
function setElectableValidators(uint256, uint256) external returns (bool);
function setMaxNumGroupsVotedFor(uint256) external returns (bool);
function setElectabilityThreshold(uint256) external returns (bool);
function distributeEpochRewards(
address,
uint256,
address,
address
) external;
function allowedToVoteOverMaxNumberOfGroups(address) external returns (bool);
function setAllowedToVoteOverMaxNumberOfGroups(bool flag) external;
function electValidatorSigners() external view returns (address[] memory);
function electNValidatorSigners(uint256, uint256) external view returns (address[] memory);
function getElectableValidators() external view returns (uint256, uint256);
function getElectabilityThreshold() external view returns (uint256);
function getNumVotesReceivable(address) external view returns (uint256);
function getTotalVotes() external view returns (uint256);
function getActiveVotes() external view returns (uint256);
function getTotalVotesByAccount(address) external view returns (uint256);
function getPendingVotesForGroupByAccount(address, address) external view returns (uint256);
function getActiveVotesForGroupByAccount(address, address) external view returns (uint256);
function getTotalVotesForGroupByAccount(address, address) external view returns (uint256);
function getActiveVoteUnitsForGroupByAccount(address, address) external view returns (uint256);
function getTotalVotesForGroup(address) external view returns (uint256);
function getActiveVotesForGroup(address) external view returns (uint256);
function getPendingVotesForGroup(address) external view returns (uint256);
function getGroupEligibility(address) external view returns (bool);
function getGroupEpochRewards(
address,
uint256,
uint256[] calldata
) external view returns (uint256);
function getGroupsVotedForByAccount(address) external view returns (address[] memory);
function getEligibleValidatorGroups() external view returns (address[] memory);
function getTotalVotesForEligibleValidatorGroups()
external
view
returns (address[] memory, uint256[] memory);
function getCurrentValidatorSigners() external view returns (address[] memory);
function canReceiveVotes(address, uint256) external view returns (bool);
function hasActivatablePendingVotes(address, address) external view returns (bool);
function maxNumGroupsVotedFor() external view returns (uint256);
function validatorSignerAddressFromCurrentSet(uint256 index) external view returns (address);
function numberValidatorsInCurrentSet() external view returns (uint256);
function getEpochNumber() external view returns (uint256);
pragma solidity 0.8.11;
}
| 16,322,696 |
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, uint256, bool) {
closed_ = _closed;
// open ,next round
if( !closed_ && round_[rID_].ended == true && activated_ == true ){
nextRound();
}
// close,finish current round
else if( closed_ && round_[rID_].ended == false && activated_ == true ){
round_[rID_].end = now - 1;
}
// close,roundId,finish
return (closed_, rID_, now > round_[rID_].end);
}
/**
* @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 (_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 ( _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 (_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 ( _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);
}
}
} | ============================================================================== _ _ _ _ | _ _ . _ . (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)=====================_|======================================================= 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/ setup local rID grab time if round is active call core if round is not active check to see if end round needs to be ran end the round (distributes pot) & start new round | function buyCore(uint256 _pID, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_) private {
uint256 _rID = rID_;
uint256 _now = now;
if (_now > (round_[_rID].strt + rndGap_) && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
if ( _now > round_[_rID].end && round_[_rID].ended == false ) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
if( !closed_ ){
nextRound();
}
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount
);
}
}
}
| 14,780,747 |
/**
*Submitted for verification at Etherscan.io on 2021-04-29
*/
// File: contracts/lib/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/lib/IERC20.sol
pragma solidity ^0.7.1;
/**
* @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/lib/introspection/IERC165.sol
pragma solidity ^0.7.1;
/**
* @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: contracts/lib/IERC721.sol
pragma solidity ^0.7.1;
/**
* @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: contracts/lib/Context.sol
pragma solidity ^0.7.1;
/*
* @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;
}
}
// File: contracts/lib/Address.sol
pragma solidity ^0.7.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
* ====
*/
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.3._
*/
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.3._
*/
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);
}
}
}
}
// File: contracts/lib/ERC20.sol
pragma solidity ^0.7.1;
/**
* @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 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 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) {
_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);
_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 spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
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);
_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) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal 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 {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 { }
}
// File: contracts/lib/SafeERC20.sol
pragma solidity ^0.7.1;
/**
* @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/NFTProtocolDEX.sol
pragma solidity ^0.7.1;
contract NFTProtocolDEX {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Multisig for emergency functions
address public multisig;
// $NFT ERC20 address
address public immutable NFTProtocolTokenAddress;
// Flat fee for NFT<->NFT trades (represented in wei of ETHER)
// Default to 0.001 ETH
uint256 public flatFee = 1000000000000000;
// Percent fee for NFT<->ERC20 trades (scaled up 10**16; 1 ether = 100% fee)
// Default to 1%
uint256 public percentFee = 10000000000000000;
// Total number of swaps
function totalSwaps() public view returns(uint) {
return swaps.length;
}
// Locks down the contract in case of emergency
bool public locked = false;
// Swap types; TODO: replace with enum
enum SwapType { _721to721, _721to20, _721to1155, _1155to721, _1155to20 }
// Maximum fee rate
uint256 private constant PERCENT_FEE_MAX = 100*10**16;
// Bypass fees with 100,000 NFT Protocol tokens
uint256 constant FEE_BYPASS = 100000 * 1 ether;
// Events
event MakeSwap(address makerContractAddress, uint256 makerTokenId, uint256 makerTokenAmount, address takerContractAddress, uint256 takerTokenId, uint256 takerTokenAmount, uint256 swapType, address indexed makerAddress, address[] whitelist, uint256 indexed id);
event TakeSwap(uint256 swapId, address takerAddress);
event SinkSwap(uint256 swapId);
event Vote(address sender, uint256 flatFee, uint256 percentFee);
// SwapData holds a struct with all information about a NFT DEX swap
struct SwapData { uint256 swapId; address makerContractAddress; uint256 makerTokenId; uint256 makerTokenAmount; address takerContractAddress; uint256 takerTokenId; uint256 takerTokenAmount; bool closed; uint256 swapType; address makerAddress; address takerAddress; bool whitelistEnabled; }
// Map a SwapData swapId with its whitelist (structs cannot have nested mappings)
mapping(uint256=>mapping(address=>bool)) public whitelist;
// Array of all swaps on the DEX
SwapData[] public swaps;
constructor(address _NFTProtocolToken, address _multisig) {
// Set multisig address and NFT Protocol token ERC20 address
multisig = _multisig;
NFTProtocolTokenAddress = _NFTProtocolToken;
}
// Create an NFT<->NFT swap
function make(address _makerContractAddress, uint256 _makerTokenId, address _takerContractAddress, uint256 _takerTokenId, uint256 _takerTokenAmount, address[] calldata _whitelist, uint256 _swapType) external {
require(_swapType == uint256(SwapType._721to721) || _swapType == uint256(SwapType._721to20), "Invalid swapType");
// Add swap to array
swaps.push(SwapData({ swapId: swaps.length, closed: false, makerContractAddress: _makerContractAddress, makerTokenId: _makerTokenId, makerTokenAmount: 0, takerContractAddress: _takerContractAddress, takerTokenId: _takerTokenId, takerTokenAmount: _takerTokenAmount, makerAddress: msg.sender, takerAddress: address(0x0), swapType: _swapType, whitelistEnabled: bool(_whitelist.length>0) }));
// Initialize whitelist mapping for this swap
for (uint256 i = 0; i < _whitelist.length; i++) whitelist[swaps.length-1][_whitelist[i]] = true;
// Transfer NFT from swap maker to DEX
IERC721 nft = IERC721(_makerContractAddress);
nft.transferFrom(msg.sender, address(this), _makerTokenId);
// Add other else statements later
emit MakeSwap(_makerContractAddress, _makerTokenId, 1, _takerContractAddress, 0, _takerTokenAmount, uint256(SwapType._721to721), msg.sender, _whitelist, swaps.length-1);
}
// Take a swap by providing requested ERC721 or requested amount of ERC20 tokens
function take(uint256 _swapId) payable external {
require(!locked, "DEX shut down");
// Get SwapData from the swap hash
SwapData memory swap = swaps[_swapId];
require(!swap.closed, "Swap has already been taken");
// Check if address attempting to fulfill swap is authorized in the whitelist
require(!swap.whitelistEnabled || whitelist[_swapId][msg.sender], "Not whitelisted");
// Close out swap
emit TakeSwap(_swapId, msg.sender);
swaps[_swapId].closed = true;
// If this is an NFT<->NFT trade then require a flat fee and execute transfer
if (swap.swapType == uint256(SwapType._721to721)) {
require(msg.value >= flatFee, "Insufficient Fee");
// Initialize tokens for transfer
IERC721 makerNFT = IERC721(swap.makerContractAddress);
IERC721 takerNFT = IERC721(swap.takerContractAddress);
IERC20 NFTProtocolToken = IERC20(NFTProtocolTokenAddress);
// Transfer makers NFT to the taker
makerNFT.transferFrom(address(this), msg.sender, swap.makerTokenId);
// Transfer takers NFT to the maker
takerNFT.transferFrom(msg.sender, swap.makerAddress, swap.takerTokenId);
}
// If this is an NFT<->ERC20 trade then require a percent fee
if (swap.swapType == uint256(SwapType._721to20)) {
// Require payment in ERC20 token requested by swap
IERC20 coin = IERC20(swap.takerContractAddress);
require(coin.balanceOf(msg.sender) >= swap.takerTokenAmount.add(calc(swap.takerTokenAmount)), "Not enough ERC20 tokens for NFT price+fee");
// Transfer ERC20 to DEX, transefer NFT to fulfiller
IERC721 makerNFT = IERC721(swap.makerContractAddress);
// Transfer taker's ERC20 tokens to maker
coin.transferFrom(msg.sender, swap.makerAddress, swap.takerTokenAmount);
// Transfer taker's ERC20 tokens fee to this contract
coin.transferFrom(msg.sender, address(this), calc(swap.takerTokenAmount));
// Transfer makers NFT to the taker
makerNFT.transferFrom(address(this), msg.sender, swap.makerTokenId);
}
}
// Cancel a swap and get the NFT back
function sink(uint256 _swapId) public {
require(!locked, "DEX shut down");
SwapData memory swap = swaps[_swapId];
require(swap.makerAddress == msg.sender, "Not swap maker");
require(swap.swapType == uint256(SwapType._721to721) || swap.swapType == uint256(SwapType._721to20), "Invalid swapType");
// Transfer NFT back to maker
IERC721 nft = IERC721(swap.makerContractAddress);
emit SinkSwap(_swapId);
swaps[_swapId].closed = true;
nft.safeTransferFrom(address(this), swap.makerAddress, swap.makerTokenId);
}
// Calculate percent fee owed for this trade
// If user has enough NFT protocol tokens then they don't have to pay fees
// Otherwise fee is a % fee based on swap output value
function calc(uint256 amount) public view returns (uint256) {
if (IERC20(NFTProtocolTokenAddress).balanceOf(msg.sender) >= FEE_BYPASS) return 0;
return amount.mul(percentFee).div(1 ether);
}
// Governance votes to set fees
function vote(uint256 _flatFee, uint256 _percentFee) external {
require(multisig == msg.sender, "Caller must be multisig");
require(_percentFee <= PERCENT_FEE_MAX, "PercentFee must be <= PERCENT_FEE_MAX");
flatFee = _flatFee;
percentFee = _percentFee;
emit Vote(msg.sender, flatFee, percentFee);
}
// Shut down the DEX in case of emergency
function lock(bool _locked) external {
require(msg.sender == multisig, "Unauthorized");
locked = _locked;
}
// Set multisig
function auth(address to) external {
require(to != address(0x0), "Cannot set to zero address");
require(msg.sender == multisig, "Unauthorized");
multisig = to;
}
// Rescue ERC20 tokens stuck on DEX
function grab(address token) external {
require(msg.sender == multisig, "Unauthorized");
IERC20(token).safeTransfer(msg.sender, IERC20(token).balanceOf(address(this)));
}
// Rescue ERC721 NFTs stuck on DEX
function pick(address nft, uint256 id) external {
require(msg.sender == multisig, "Unauthorized");
IERC721(nft).safeTransferFrom(address(this), msg.sender, id);
}
// Rescue Ether stuck on DEX
function lift() external {
require(msg.sender == multisig, "Unauthorized");
address payable to = msg.sender;
to.transfer(address(this).balance);
}
} | Rescue Ether stuck on DEX | function lift() external {
require(msg.sender == multisig, "Unauthorized");
address payable to = msg.sender;
to.transfer(address(this).balance);
}
| 15,276,675 |
./full_match/3/0x11F724A9A44D5728DA778C1a7DF2DEdba34dca2B/sources/localhost/Lock3rPresale.sol | manager can reclaim unsold tokens / calculate the amount of tokens that haven not been sold and settled and are thus reclaimable: transfer the tokens to the manager | function managerReclaim(uint256 _amount) public onlyManager {
uint256 unreclaimable = totalSold.sub(totalSettled);
uint256 reclaimable = LK3R.balanceOf(address(this)).sub(unreclaimable);
require(_amount <= reclaimable, "cannot withdraw already sold tokens");
LK3R.transfer(msg.sender, _amount);
totalForSale = totalForSale.sub(_amount);
}
| 8,212,847 |
./full_match/4/0xedE6d3397244D45675d48C5149913536f1d098bb/sources/browser/204_token.sol | Interface of the ERC20 standard as defined in the EIP./ | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, 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);
SPDX-License-Identifier: CC-BY-4.0
}
| 698,085 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Aggregator.sol";
import "../interfaces/IWhiteAggregator.sol";
contract WhiteAggregator is Aggregator, IWhiteAggregator {
struct SubmissionInfo {
bool confirmed; // whether is confirmed
uint256 confirmations; // received confirmations count
mapping(address => bool) hasVerified; // verifier => has already voted
}
mapping(bytes32 => SubmissionInfo) public getMintInfo; // mint id => submission info
mapping(bytes32 => SubmissionInfo) public getBurntInfo; // burnt id => submission info
event Confirmed(bytes32 submissionId, address operator); // emitted once the submission is confirmed
event SubmissionApproved(bytes32 submissionId); // emitted once the submission is confirmed
/// @dev Constructor that initializes the most important configurations.
/// @param _minConfirmations Minimal required confirmations.
/// @param _payment Oracle reward.
/// @param _link Link token to pay to oracles.
constructor(
uint256 _minConfirmations,
uint128 _payment,
IERC20 _link
) Aggregator(_minConfirmations, _payment, _link) {}
/// @dev Confirms the mint request.
/// @param _mintId Submission identifier.
function submitMint(bytes32 _mintId) external override onlyOracle {
SubmissionInfo storage mintInfo = getMintInfo[_mintId];
require(!mintInfo.hasVerified[msg.sender], "submit: submitted already");
mintInfo.confirmations += 1;
mintInfo.hasVerified[msg.sender] = true;
if (mintInfo.confirmations >= minConfirmations) {
mintInfo.confirmed = true;
emit SubmissionApproved(_mintId);
}
_payOracle(msg.sender);
emit Confirmed(_mintId, msg.sender);
}
/// @dev Confirms the burnnt request.
/// @param _burntId Submission identifier.
function submitBurn(bytes32 _burntId) external override onlyOracle {
SubmissionInfo storage burnInfo = getBurntInfo[_burntId];
require(!burnInfo.hasVerified[msg.sender], "submit: submitted already");
burnInfo.confirmations += 1;
burnInfo.hasVerified[msg.sender] = true;
if (burnInfo.confirmations >= minConfirmations) {
burnInfo.confirmed = true;
emit SubmissionApproved(_burntId);
}
emit Confirmed(_burntId, msg.sender);
_payOracle(msg.sender);
}
/// @dev Returns whether mint request is confirmed.
/// @param _mintId Submission identifier.
/// @return Whether mint request is confirmed.
function isMintConfirmed(bytes32 _mintId)
external
view
override
returns (bool)
{
return getMintInfo[_mintId].confirmed;
}
/// @dev Returns whether burnnt request is confirmed.
/// @param _burntId Submission identifier.
/// @return Whether burnnt request is confirmed.
function isBurntConfirmed(bytes32 _burntId)
external
view
override
returns (bool)
{
return getBurntInfo[_burntId].confirmed;
}
}
| Confirms the burnnt request. _burntId Submission identifier. | function submitBurn(bytes32 _burntId) external override onlyOracle {
SubmissionInfo storage burnInfo = getBurntInfo[_burntId];
require(!burnInfo.hasVerified[msg.sender], "submit: submitted already");
burnInfo.confirmations += 1;
burnInfo.hasVerified[msg.sender] = true;
if (burnInfo.confirmations >= minConfirmations) {
burnInfo.confirmed = true;
emit SubmissionApproved(_burntId);
}
emit Confirmed(_burntId, msg.sender);
_payOracle(msg.sender);
}
| 12,561,100 |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
interface DharmaTradeReserveV9Interface {
event ROLEMODIFIED858(Role indexed role, address account); //inject NONSTANDARD NAMING
event ROLEPAUSED516(Role indexed role); //inject NONSTANDARD NAMING
event ROLEUNPAUSED425(Role indexed role); //inject NONSTANDARD NAMING
event ETHERRECEIVED855(address sender, uint256 amount); //inject NONSTANDARD NAMING
enum Role { // #
DEPOSIT_MANAGER, // 0
ADJUSTER, // 1
WITHDRAWAL_MANAGER, // 2
RESERVE_TRADER, // 3
PAUSER // 4
}
struct RoleStatus {
address account;
bool paused;
}
function TRADEDAIFORETHER899( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEDAIFORETHERV2950( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEETHERFORDAI795( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function TRADEETHERFORDAIV2625( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount, uint256 deadline
) external payable returns (uint256 totalDaiBought);
function TRADEDAIFORTOKEN107( //inject NONSTANDARD NAMING
address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiSold);
function TRADETOKENFORDAI864( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiBought);
function TRADETOKENFORETHER84( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalEtherBought);
function TRADEETHERFORTOKEN818( //inject NONSTANDARD NAMING
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold);
function TRADEETHERFORTOKENUSINGETHERIZER867( //inject NONSTANDARD NAMING
address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalEtherSold);
function TRADEDAIFORETHERUSINGRESERVES556( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEDAIFORETHERUSINGRESERVESV2121( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalDaiSold);
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI322( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV298( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function TRADEDAIFORTOKENUSINGRESERVES528( //inject NONSTANDARD NAMING
address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiSold);
function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI549( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted);
function TRADETOKENFORETHERUSINGRESERVES915( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalEtherBought);
function TRADEETHERFORTOKENUSINGRESERVES405( //inject NONSTANDARD NAMING
address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalEtherSold);
function FINALIZEETHERDEPOSIT298( //inject NONSTANDARD NAMING
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external;
function FINALIZEDAIDEPOSIT931( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external;
function FINALIZEDHARMADAIDEPOSIT237( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external;
function MINT835(uint256 daiAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING
function REDEEM834(uint256 dDaiAmount) external returns (uint256 daiReceived); //inject NONSTANDARD NAMING
function TRADEDDAIFORUSDC353( //inject NONSTANDARD NAMING
uint256 daiEquivalentAmount, uint256 quotedUSDCAmount
) external returns (uint256 usdcReceived);
function TRADEUSDCFORDDAI141( //inject NONSTANDARD NAMING
uint256 usdcAmount, uint256 quotedDaiEquivalentAmount
) external returns (uint256 dDaiMinted);
function WITHDRAWUSDC678(address recipient, uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDAI49(address recipient, uint256 daiAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDHARMADAI777(address recipient, uint256 dDaiAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWUSDCTOPRIMARYRECIPIENT422(uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWDAITOPRIMARYRECIPIENT762(uint256 usdcAmount) external; //inject NONSTANDARD NAMING
function WITHDRAWETHER204( //inject NONSTANDARD NAMING
address payable recipient, uint256 etherAmount
) external;
function WITHDRAW439( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, uint256 amount
) external returns (bool success);
function CALLANY778( //inject NONSTANDARD NAMING
address payable target, uint256 amount, bytes calldata data
) external returns (bool ok, bytes memory returnData);
function SETDAILIMIT345(uint256 daiAmount) external; //inject NONSTANDARD NAMING
function SETETHERLIMIT550(uint256 daiAmount) external; //inject NONSTANDARD NAMING
function SETPRIMARYUSDCRECIPIENT259(address recipient) external; //inject NONSTANDARD NAMING
function SETPRIMARYDAIRECIPIENT972(address recipient) external; //inject NONSTANDARD NAMING
function SETROLE712(Role role, address account) external; //inject NONSTANDARD NAMING
function REMOVEROLE29(Role role) external; //inject NONSTANDARD NAMING
function PAUSE504(Role role) external; //inject NONSTANDARD NAMING
function UNPAUSE768(Role role) external; //inject NONSTANDARD NAMING
function ISPAUSED423(Role role) external view returns (bool paused); //inject NONSTANDARD NAMING
function ISROLE511(Role role) external view returns (bool hasRole); //inject NONSTANDARD NAMING
function ISDHARMASMARTWALLET695( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet);
function GETDEPOSITMANAGER250() external view returns (address depositManager); //inject NONSTANDARD NAMING
function GETADJUSTER715() external view returns (address adjuster); //inject NONSTANDARD NAMING
function GETRESERVETRADER735() external view returns (address reserveTrader); //inject NONSTANDARD NAMING
function GETWITHDRAWALMANAGER7() external view returns (address withdrawalManager); //inject NONSTANDARD NAMING
function GETPAUSER73() external view returns (address pauser); //inject NONSTANDARD NAMING
function GETRESERVES254() external view returns ( //inject NONSTANDARD NAMING
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
);
function GETDAILIMIT529() external view returns ( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 dDaiAmount
);
function GETETHERLIMIT792() external view returns (uint256 etherAmount); //inject NONSTANDARD NAMING
function GETPRIMARYUSDCRECIPIENT771() external view returns ( //inject NONSTANDARD NAMING
address recipient
);
function GETPRIMARYDAIRECIPIENT209() external view returns ( //inject NONSTANDARD NAMING
address recipient
);
function GETIMPLEMENTATION393() external view returns (address implementation); //inject NONSTANDARD NAMING
function GETVERSION945() external view returns (uint256 version); //inject NONSTANDARD NAMING
}
interface ERC20Interface {
function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE301(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE335(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER424(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM59(address, address, uint256) external returns (bool); //inject NONSTANDARD NAMING
}
interface DTokenInterface {
function MINT835(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING
function REDEEM834(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING110(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING
function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING111(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER424(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE301(address, uint256) external returns (bool); //inject NONSTANDARD NAMING
function EXCHANGERATECURRENT826() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface TradeHelperInterface {
function TRADEUSDCFORDDAI141(uint256 amountUSDC, uint256 quotedDaiEquivalentAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING
function TRADEDDAIFORUSDC353(uint256 amountDai, uint256 quotedUSDCAmount) external returns (uint256 usdcReceived); //inject NONSTANDARD NAMING
function GETEXPECTEDDAI468(uint256 usdc) external view returns (uint256 dai); //inject NONSTANDARD NAMING
function GETEXPECTEDUSDC440(uint256 dai) external view returns (uint256 usdc); //inject NONSTANDARD NAMING
}
interface UniswapV1Interface {
function ETHTOTOKENSWAPINPUT251( //inject NONSTANDARD NAMING
uint256 minTokens, uint256 deadline
) external payable returns (uint256 tokensBought);
function TOKENTOETHTRANSFEROUTPUT929( //inject NONSTANDARD NAMING
uint256 ethBought, uint256 maxTokens, uint256 deadline, address recipient
) external returns (uint256 tokensSold);
}
interface UniswapV2Interface {
function SWAPTOKENSFOREXACTTOKENS91( //inject NONSTANDARD NAMING
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPEXACTTOKENSFORTOKENS457( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPEXACTTOKENSFORETH769( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPTOKENSFOREXACTETH731( //inject NONSTANDARD NAMING
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function SWAPETHFOREXACTTOKENS5( //inject NONSTANDARD NAMING
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function SWAPEXACTETHFORTOKENS903( //inject NONSTANDARD NAMING
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface EtherReceiverInterface {
function SETTLEETHER955() external; //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD510(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function MUL1(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, "SafeMath: division by zero");
return a / b;
}
}
contract TwoStepOwnable {
event OWNERSHIPTRANSFERRED461( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
address private _owner;
address private _newPotentialOwner;
function TRANSFEROWNERSHIP1000(address newOwner) external ONLYOWNER389 { //inject NONSTANDARD NAMING
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
function CANCELOWNERSHIPTRANSFER705() external ONLYOWNER389 { //inject NONSTANDARD NAMING
delete _newPotentialOwner;
}
function ACCEPTOWNERSHIP63() external { //inject NONSTANDARD NAMING
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OWNERSHIPTRANSFERRED461(_owner, msg.sender);
_owner = msg.sender;
}
function OWNER109() external view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
function ISOWNER823() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
modifier ONLYOWNER389() { //inject NONSTANDARD NAMING
require(ISOWNER823(), "TwoStepOwnable: caller is not the owner.");
_;
}
}
contract DharmaTradeReserveV9ImplementationStaging is DharmaTradeReserveV9Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a "primary recipient" the withdrawal manager can transfer Dai to.
address private _primaryDaiRecipient;
// Maintain a "primary recipient" the withdrawal manager can transfer USDC to.
address private _primaryUSDCRecipient;
// Maintain a maximum allowable transfer size (in Dai) for the deposit manager.
uint256 private _daiLimit;
// Maintain a maximum allowable transfer size (in Ether) for the deposit manager.
uint256 private _etherLimit;
bool private _originatesFromReserveTrader; // unused, don't change storage layout
uint256 private constant _version934 = 8; //inject NONSTANDARD NAMING
// This contract interacts with USDC, Dai, and Dharma Dai.
ERC20Interface internal constant _usdc172 = ERC20Interface( //inject NONSTANDARD NAMING
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ERC20Interface internal constant _dai939 = ERC20Interface( //inject NONSTANDARD NAMING
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
ERC20Interface internal constant _etherizer566 = ERC20Interface( //inject NONSTANDARD NAMING
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
DTokenInterface internal constant _ddai325 = DTokenInterface( //inject NONSTANDARD NAMING
0x00000000001876eB1444c986fD502e618c587430
);
TradeHelperInterface internal constant _trade_helper648 = TradeHelperInterface( //inject NONSTANDARD NAMING
0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d
);
UniswapV1Interface internal constant _uniswap_dai496 = UniswapV1Interface( //inject NONSTANDARD NAMING
0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667
);
UniswapV2Interface internal constant _uniswap_router877 = UniswapV2Interface( //inject NONSTANDARD NAMING
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
EtherReceiverInterface internal constant _eth_receiver459 = EtherReceiverInterface( //inject NONSTANDARD NAMING
0xaf84687D21736F5E06f738c6F065e88890465E7c
);
address internal constant _weth740 = address( //inject NONSTANDARD NAMING
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
);
// The "Create2 Header" is used to compute smart wallet deployment addresses.
bytes21 internal constant _create2_header376 = bytes21( //inject NONSTANDARD NAMING
0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory
);
// The "Wallet creation code" header & footer are also used to derive wallets.
bytes internal constant _wallet_creation_code_header138 = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; //inject NONSTANDARD NAMING
bytes28 internal constant _wallet_creation_code_footer303 = bytes28( //inject NONSTANDARD NAMING
0x00000000000000000000000000000000000000000000000000000000
);
// Include a payable fallback so that the contract can receive Ether payments.
function () external payable {
emit ETHERRECEIVED855(msg.sender, msg.value);
}
function INITIALIZE669() external { //inject NONSTANDARD NAMING
// Approve Uniswap router to transfer Dai on behalf of this contract.
if (_dai939.ALLOWANCE335(address(this), address(_uniswap_router877)) != uint256(-1)) {
bool ok = _dai939.APPROVE301(address(_uniswap_router877), uint256(-1));
require(ok, "Dai approval for Uniswap router failed.");
}
}
function TRADEDAIFORETHER899( //inject NONSTANDARD NAMING
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount);
// Trade the Dai for the quoted Ether amount on Uniswap and send to caller.
totalDaiSold = _uniswap_dai496.TOKENTOETHTRANSFEROUTPUT929(
quotedEtherAmount, daiAmount, deadline, msg.sender
);
}
function TRADEDAIFORETHERV2950( //inject NONSTANDARD NAMING
uint256 daiAmount,
uint256 quotedEtherAmount,
uint256 deadline
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount);
// Establish path from Dai to Ether.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(_dai939), _weth740, false
);
// Trade Dai for quoted Ether amount on Uniswap (send to the caller).
amounts = _uniswap_router877.SWAPTOKENSFOREXACTETH731(
quotedEtherAmount, daiAmount, path, msg.sender, deadline
);
totalDaiSold = amounts[0];
}
function TRADETOKENFORETHER84( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline
) external returns (uint256 totalEtherBought) {
// Transfer the tokens from the caller and revert on failure.
_TRANSFERINTOKEN213(token, msg.sender, tokenAmount);
// Approve Uniswap router to transfer tokens on behalf of this contract.
_GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token);
// Establish path from target token to Ether.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(token), _weth740, false
);
// Trade tokens for quoted Ether amount on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPEXACTTOKENSFORETH769(
tokenAmount, quotedEtherAmount, path, address(this), deadline
);
totalEtherBought = amounts[1];
// Send quoted Ether amount to caller and revert with reason on failure.
(bool ok, ) = msg.sender.call.value(quotedEtherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function TRADEDAIFORTOKEN107( //inject NONSTANDARD NAMING
address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiSold) {
// Transfer the Dai from the caller and revert on failure.
_TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount);
// Establish path (direct or routed through Ether) from Dai to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(_dai939), token, routeThroughEther
);
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
amounts = _uniswap_router877.SWAPTOKENSFOREXACTTOKENS91(
quotedTokenAmount, daiAmount, path, msg.sender, deadline
);
totalDaiSold = amounts[0];
}
function TRADEDAIFORETHERUSINGRESERVES556( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai939.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai325.REDEEMUNDERLYING110(additionalDaiRequired);
}
// Trade the Dai for the quoted Ether amount on Uniswap.
totalDaiSold = _uniswap_dai496.TOKENTOETHTRANSFEROUTPUT929(
quotedEtherAmount,
daiAmountFromReserves,
deadline,
address(_eth_receiver459)
);
// Move the Ether from the receiver to this contract (gas workaround).
_eth_receiver459.SETTLEETHER955();
}
function TRADEDAIFORETHERUSINGRESERVESV2121( //inject NONSTANDARD NAMING
uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai939.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai325.REDEEMUNDERLYING110(additionalDaiRequired);
}
// Establish path from Dai to Ether.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(_dai939), _weth740, false
);
// Trade Dai for quoted Ether amount on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPTOKENSFOREXACTETH731(
quotedEtherAmount, daiAmountFromReserves, path, address(this), deadline
);
totalDaiSold = amounts[0];
}
function TRADETOKENFORETHERUSINGRESERVES915( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token);
// Establish path from target token to Ether.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(token), _weth740, false
);
// Trade tokens for quoted Ether amount on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPEXACTTOKENSFORETH769(
tokenAmountFromReserves, quotedEtherAmount, path, address(this), deadline
);
totalEtherBought = amounts[1];
}
function TRADEETHERFORDAI795( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Trade the Ether for the quoted Dai amount on Uniswap.
totalDaiBought = _uniswap_dai496.ETHTOTOKENSWAPINPUT251.value(msg.value)(
quotedDaiAmount, deadline
);
// Transfer the Dai to the caller and revert on failure.
_TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount);
}
function TRADEETHERFORDAIV2625( //inject NONSTANDARD NAMING
uint256 quotedDaiAmount,
uint256 deadline
) external payable returns (uint256 totalDaiBought) {
// Establish path from Ether to Dai.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(_dai939), false
);
// Trade Ether for Dai on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPEXACTETHFORTOKENS903.value(msg.value)(
quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
// Transfer the Dai to the caller and revert on failure.
_TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount);
}
function TRADEETHERFORTOKEN818( //inject NONSTANDARD NAMING
address token, uint256 quotedTokenAmount, uint256 deadline
) external payable returns (uint256 totalEtherSold) {
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(token), false
);
// Trade Ether for quoted token amount on Uniswap and send to caller.
amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(msg.value)(
quotedTokenAmount, path, msg.sender, deadline
);
totalEtherSold = amounts[0];
}
function TRADEETHERFORTOKENUSINGETHERIZER867( //inject NONSTANDARD NAMING
address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline
) external returns (uint256 totalEtherSold) {
// Transfer the Ether from the caller and revert on failure.
_TRANSFERINTOKEN213(_etherizer566, msg.sender, etherAmount);
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(token), false
);
// Trade Ether for quoted token amount on Uniswap and send to caller.
amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(etherAmount)(
quotedTokenAmount, path, msg.sender, deadline
);
totalEtherSold = amounts[0];
}
function TRADETOKENFORDAI864( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther
) external returns (uint256 totalDaiBought) {
// Transfer the token from the caller and revert on failure.
_TRANSFERINTOKEN213(token, msg.sender, tokenAmount);
// Approve Uniswap router to transfer tokens on behalf of this contract.
_GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token);
// Establish path (direct or routed through Ether) from target token to Dai.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(token), address(_dai939), routeThroughEther
);
// Trade the Dai for the quoted token amount on Uniswap and send to caller.
amounts = _uniswap_router877.SWAPEXACTTOKENSFORTOKENS457(
tokenAmount, quotedDaiAmount, path, msg.sender, deadline
);
totalDaiBought = amounts[path.length - 1];
// Transfer the Dai to the caller and revert on failure.
_TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount);
}
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI322( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Trade the Ether for the quoted Dai amount on Uniswap.
totalDaiBought = _uniswap_dai496.ETHTOTOKENSWAPINPUT251.value(
etherAmountFromReserves
)(
quotedDaiAmount, deadline
);
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai325.MINT835(totalDaiBought);
}
function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV298( //inject NONSTANDARD NAMING
uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Establish path from Ether to Dai.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(_dai939), false
);
// Trade Ether for Dai on Uniswap (send to this contract).
amounts = _uniswap_router877.SWAPEXACTETHFORTOKENS903.value(
etherAmountFromReserves
)(
quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[1];
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai325.MINT835(totalDaiBought);
}
function TRADEETHERFORTOKENUSINGRESERVES405( //inject NONSTANDARD NAMING
address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) {
// Establish path from Ether to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
_weth740, address(token), false
);
// Trade Ether for quoted token amount on Uniswap and send to this contract.
amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(etherAmountFromReserves)(
quotedTokenAmount, path, address(this), deadline
);
totalEtherSold = amounts[0];
}
function TRADEDAIFORTOKENUSINGRESERVES528( //inject NONSTANDARD NAMING
address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) {
// Redeem dDai if the current Dai balance is less than is required.
uint256 daiBalance = _dai939.BALANCEOF395(address(this));
if (daiBalance < daiAmountFromReserves) {
uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance;
_ddai325.REDEEMUNDERLYING110(additionalDaiRequired);
}
// Establish path (direct or routed through Ether) from Dai to target token.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(_dai939), address(token), routeThroughEther
);
// Trade the Dai for the quoted token amount on Uniswap.
amounts = _uniswap_router877.SWAPTOKENSFOREXACTTOKENS91(
quotedTokenAmount, daiAmountFromReserves, path, address(this), deadline
);
totalDaiSold = amounts[0];
}
function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI549( //inject NONSTANDARD NAMING
ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther
) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (
uint256 totalDaiBought, uint256 totalDDaiMinted
) {
// Approve Uniswap router to transfer tokens on behalf of this contract.
_GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token);
// Establish path (direct or routed through Ether) from target token to Dai.
(address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796(
address(token), address(_dai939), routeThroughEther
);
// Trade the Dai for the quoted token amount on Uniswap.
amounts = _uniswap_router877.SWAPEXACTTOKENSFORTOKENS457(
tokenAmountFromReserves, quotedDaiAmount, path, address(this), deadline
);
totalDaiBought = amounts[path.length - 1];
// Mint dDai using the received Dai.
totalDDaiMinted = _ddai325.MINT835(totalDaiBought);
}
function FINALIZEDAIDEPOSIT931( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 daiAmount
) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ENSURESMARTWALLET516(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(daiAmount < _daiLimit, "Transfer size exceeds the limit.");
// Transfer the Dai to the specified smart wallet.
_TRANSFERTOKEN930(_dai939, smartWallet, daiAmount);
}
function FINALIZEDHARMADAIDEPOSIT237( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey, uint256 dDaiAmount
) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ENSURESMARTWALLET516(smartWallet, initialUserSigningKey);
// Get the current dDai exchange rate.
uint256 exchangeRate = _ddai325.EXCHANGERATECURRENT826();
// Ensure that an exchange rate was actually returned.
require(exchangeRate != 0, "Could not retrieve dDai exchange rate.");
// Get the equivalent Dai amount of the transfer.
uint256 daiEquivalent = (dDaiAmount.MUL1(exchangeRate)) / 1e18;
// Ensure that the amount to transfer is lower than the limit.
require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit.");
// Transfer the dDai to the specified smart wallet.
_TRANSFERTOKEN930(ERC20Interface(address(_ddai325)), smartWallet, dDaiAmount);
}
function FINALIZEETHERDEPOSIT298( //inject NONSTANDARD NAMING
address payable smartWallet,
address initialUserSigningKey,
uint256 etherAmount
) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) {
// Ensure that the recipient is indeed a smart wallet.
_ENSURESMARTWALLET516(smartWallet, initialUserSigningKey);
// Ensure that the amount to transfer is lower than the limit.
require(etherAmount < _etherLimit, "Transfer size exceeds the limit.");
// Transfer the Ether to the specified smart wallet.
bool ok;
(ok, ) = smartWallet.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function MINT835( //inject NONSTANDARD NAMING
uint256 daiAmount
) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 dDaiMinted) {
// Use the specified amount of Dai to mint dDai.
dDaiMinted = _ddai325.MINT835(daiAmount);
}
function REDEEM834( //inject NONSTANDARD NAMING
uint256 dDaiAmount
) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 daiReceived) {
// Redeem the specified amount of dDai for Dai.
daiReceived = _ddai325.REDEEM834(dDaiAmount);
}
function TRADEUSDCFORDDAI141( //inject NONSTANDARD NAMING
uint256 usdcAmount,
uint256 quotedDaiEquivalentAmount
) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 dDaiMinted) {
dDaiMinted = _trade_helper648.TRADEUSDCFORDDAI141(
usdcAmount, quotedDaiEquivalentAmount
);
}
function TRADEDDAIFORUSDC353( //inject NONSTANDARD NAMING
uint256 daiEquivalentAmount,
uint256 quotedUSDCAmount
) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 usdcReceived) {
usdcReceived = _trade_helper648.TRADEDDAIFORUSDC353(
daiEquivalentAmount, quotedUSDCAmount
);
}
function WITHDRAWUSDCTOPRIMARYRECIPIENT422( //inject NONSTANDARD NAMING
uint256 usdcAmount
) external ONLYOWNEROR665(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryUSDCRecipient;
require(
primaryRecipient != address(0), "No USDC primary recipient currently set."
);
// Transfer the supplied USDC amount to the primary recipient.
_TRANSFERTOKEN930(_usdc172, primaryRecipient, usdcAmount);
}
function WITHDRAWDAITOPRIMARYRECIPIENT762( //inject NONSTANDARD NAMING
uint256 daiAmount
) external ONLYOWNEROR665(Role.WITHDRAWAL_MANAGER) {
// Get the current primary recipient.
address primaryRecipient = _primaryDaiRecipient;
require(
primaryRecipient != address(0), "No Dai primary recipient currently set."
);
// Transfer the supplied Dai amount to the primary recipient.
_TRANSFERTOKEN930(_dai939, primaryRecipient, daiAmount);
}
function WITHDRAWUSDC678( //inject NONSTANDARD NAMING
address recipient, uint256 usdcAmount
) external ONLYOWNER389 {
// Transfer the USDC to the specified recipient.
_TRANSFERTOKEN930(_usdc172, recipient, usdcAmount);
}
function WITHDRAWDAI49( //inject NONSTANDARD NAMING
address recipient, uint256 daiAmount
) external ONLYOWNER389 {
// Transfer the Dai to the specified recipient.
_TRANSFERTOKEN930(_dai939, recipient, daiAmount);
}
function WITHDRAWDHARMADAI777( //inject NONSTANDARD NAMING
address recipient, uint256 dDaiAmount
) external ONLYOWNER389 {
// Transfer the dDai to the specified recipient.
_TRANSFERTOKEN930(ERC20Interface(address(_ddai325)), recipient, dDaiAmount);
}
function WITHDRAWETHER204( //inject NONSTANDARD NAMING
address payable recipient, uint256 etherAmount
) external ONLYOWNER389 {
bool ok;
// Transfer the Ether to the specified recipient.
(ok, ) = recipient.call.value(etherAmount)("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function WITHDRAW439( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, uint256 amount
) external ONLYOWNER389 returns (bool success) {
// Transfer the token to the specified recipient.
success = token.TRANSFER424(recipient, amount);
}
function CALLANY778( //inject NONSTANDARD NAMING
address payable target, uint256 amount, bytes calldata data
) external ONLYOWNER389 returns (bool ok, bytes memory returnData) {
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
}
function SETDAILIMIT345(uint256 daiAmount) external ONLYOWNER389 { //inject NONSTANDARD NAMING
// Set the new limit.
_daiLimit = daiAmount;
}
function SETETHERLIMIT550(uint256 etherAmount) external ONLYOWNER389 { //inject NONSTANDARD NAMING
// Set the new limit.
_etherLimit = etherAmount;
}
function SETPRIMARYUSDCRECIPIENT259(address recipient) external ONLYOWNER389 { //inject NONSTANDARD NAMING
// Set the new primary recipient.
_primaryUSDCRecipient = recipient;
}
function SETPRIMARYDAIRECIPIENT972(address recipient) external ONLYOWNER389 { //inject NONSTANDARD NAMING
// Set the new primary recipient.
_primaryDaiRecipient = recipient;
}
function PAUSE504(Role role) external ONLYOWNEROR665(Role.PAUSER) { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role in question is already paused.");
storedRoleStatus.paused = true;
emit ROLEPAUSED516(role);
}
function UNPAUSE768(Role role) external ONLYOWNER389 { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role in question is already unpaused.");
storedRoleStatus.paused = false;
emit ROLEUNPAUSED425(role);
}
function SETROLE712(Role role, address account) external ONLYOWNER389 { //inject NONSTANDARD NAMING
require(account != address(0), "Must supply an account.");
_SETROLE905(role, account);
}
function REMOVEROLE29(Role role) external ONLYOWNER389 { //inject NONSTANDARD NAMING
_SETROLE905(role, address(0));
}
function ISPAUSED423(Role role) external view returns (bool paused) { //inject NONSTANDARD NAMING
paused = _ISPAUSED128(role);
}
function ISROLE511(Role role) external view returns (bool hasRole) { //inject NONSTANDARD NAMING
hasRole = _ISROLE24(role);
}
function ISDHARMASMARTWALLET695( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) external view returns (bool dharmaSmartWallet) {
dharmaSmartWallet = _ISSMARTWALLET926(smartWallet, initialUserSigningKey);
}
function GETDEPOSITMANAGER250() external view returns (address depositManager) { //inject NONSTANDARD NAMING
depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account;
}
function GETADJUSTER715() external view returns (address adjuster) { //inject NONSTANDARD NAMING
adjuster = _roles[uint256(Role.ADJUSTER)].account;
}
function GETRESERVETRADER735() external view returns (address reserveTrader) { //inject NONSTANDARD NAMING
reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account;
}
function GETWITHDRAWALMANAGER7() external view returns (address withdrawalManager) { //inject NONSTANDARD NAMING
withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account;
}
function GETPAUSER73() external view returns (address pauser) { //inject NONSTANDARD NAMING
pauser = _roles[uint256(Role.PAUSER)].account;
}
function GETRESERVES254() external view returns ( //inject NONSTANDARD NAMING
uint256 dai, uint256 dDai, uint256 dDaiUnderlying
) {
dai = _dai939.BALANCEOF395(address(this));
dDai = _ddai325.BALANCEOF395(address(this));
dDaiUnderlying = _ddai325.BALANCEOFUNDERLYING111(address(this));
}
function GETDAILIMIT529() external view returns ( //inject NONSTANDARD NAMING
uint256 daiAmount, uint256 dDaiAmount
) {
daiAmount = _daiLimit;
dDaiAmount = (daiAmount.MUL1(1e18)).DIV802(_ddai325.EXCHANGERATECURRENT826());
}
function GETETHERLIMIT792() external view returns (uint256 etherAmount) { //inject NONSTANDARD NAMING
etherAmount = _etherLimit;
}
function GETPRIMARYUSDCRECIPIENT771() external view returns ( //inject NONSTANDARD NAMING
address recipient
) {
recipient = _primaryUSDCRecipient;
}
function GETPRIMARYDAIRECIPIENT209() external view returns ( //inject NONSTANDARD NAMING
address recipient
) {
recipient = _primaryDaiRecipient;
}
function GETIMPLEMENTATION393() external view returns ( //inject NONSTANDARD NAMING
address implementation
) {
(bool ok, bytes memory returnData) = address(
0x481B1a16E6675D33f8BBb3a6A58F5a9678649718
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
function GETVERSION945() external view returns (uint256 version) { //inject NONSTANDARD NAMING
version = _version934;
}
function _GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(ERC20Interface token) internal { //inject NONSTANDARD NAMING
// Approve Uniswap router to transfer tokens on behalf of this contract.
if (token.ALLOWANCE335(address(this), address(_uniswap_router877)) != uint256(-1)) {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(
token.APPROVE301.selector, address(_uniswap_router877), uint256(-1)
)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Token approval for Uniswap router failed."
);
}
}
function _SETROLE905(Role role, address account) internal { //inject NONSTANDARD NAMING
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit ROLEMODIFIED858(role, account);
}
}
function _ISROLE24(Role role) internal view returns (bool hasRole) { //inject NONSTANDARD NAMING
hasRole = msg.sender == _roles[uint256(role)].account;
}
function _ISPAUSED128(Role role) internal view returns (bool paused) { //inject NONSTANDARD NAMING
paused = _roles[uint256(role)].paused;
}
function _ISSMARTWALLET926( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) internal pure returns (bool) {
// Derive the keccak256 hash of the smart wallet initialization code.
bytes32 initCodeHash = keccak256(
abi.encodePacked(
_wallet_creation_code_header138,
initialUserSigningKey,
_wallet_creation_code_footer303
)
);
// Attempt to derive a smart wallet address that matches the one provided.
address target;
for (uint256 nonce = 0; nonce < 10; nonce++) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using all inputs.
abi.encodePacked( // pack all inputs to the hash together.
_create2_header376, // pass in control character + factory address.
nonce, // pass in current nonce as the salt.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Exit early if the provided smart wallet matches derived target address.
if (target == smartWallet) {
return true;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
// Explicity recognize no target was found matching provided smart wallet.
return false;
}
function _TRANSFERTOKEN930(ERC20Interface token, address to, uint256 amount) internal { //inject NONSTANDARD NAMING
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(token.TRANSFER424.selector, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer out failed.'
);
}
function _TRANSFERINTOKEN213(ERC20Interface token, address from, uint256 amount) internal { //inject NONSTANDARD NAMING
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(token.TRANSFERFROM59.selector, from, address(this), amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'Transfer in failed.'
);
}
function _ENSURESMARTWALLET516( //inject NONSTANDARD NAMING
address smartWallet, address initialUserSigningKey
) internal view {
require(
_ISSMARTWALLET926(smartWallet, initialUserSigningKey),
"Could not resolve smart wallet using provided signing key."
);
}
function _CREATEPATHANDAMOUNTS796( //inject NONSTANDARD NAMING
address start, address end, bool routeThroughEther
) internal pure returns (address[] memory, uint256[] memory) {
uint256 pathLength = routeThroughEther ? 3 : 2;
address[] memory path = new address[](pathLength);
path[0] = start;
if (routeThroughEther) {
path[1] = _weth740;
}
path[pathLength - 1] = end;
return (path, new uint256[](pathLength));
}
modifier ONLYOWNEROR665(Role role) { //inject NONSTANDARD NAMING
if (!ISOWNER823()) {
require(_ISROLE24(role), "Caller does not have a required role.");
require(!_ISPAUSED128(role), "Role in question is currently paused.");
}
_;
}
} | inject NONSTANDARD NAMING | function GETPAUSER73() external view returns (address pauser); | 12,960,408 |
./full_match/1/0x0A3DE08afA286e852473B053d46f5c7F226b8C61/sources/contracts/MintingRouter.sol | Mints NFTs during whitelist sale rounds. Requires the current sale round to be a WHITELIST round. recipient The address that will receive the minted NFT. quantity The number of NFTs to mint. signature The signature of a whitelisted minter./ | function whitelistMint(
address recipient,
uint256 quantity,
bytes calldata signature
) external payable requiresWhitelist(signature) nonReentrant {
require(saleRound.saleType == SaleRoundType.WHITELIST, "Not a whitelist round");
_mint(msg.value, recipient, quantity);
}
| 17,013,518 |
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
/*
Copyright 2018 dYdX Trading 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.
*/
// File: openzeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a >= _b ? _a : _b;
}
function min64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a < _b ? _a : _b;
}
function max256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a >= _b ? _a : _b;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: openzeppelin-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 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;
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 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-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 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;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(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;
}
}
// File: contracts/lib/AccessControlledBase.sol
/**
* @title AccessControlledBase
* @author dYdX
*
* Base functionality for access control. Requires an implementation to
* provide a way to grant and optionally revoke access
*/
contract AccessControlledBase {
// ============ State Variables ============
mapping (address => bool) public authorized;
// ============ Events ============
event AccessGranted(
address who
);
event AccessRevoked(
address who
);
// ============ Modifiers ============
modifier requiresAuthorization() {
require(
authorized[msg.sender],
"AccessControlledBase#requiresAuthorization: Sender not authorized"
);
_;
}
}
// File: contracts/lib/StaticAccessControlled.sol
/**
* @title StaticAccessControlled
* @author dYdX
*
* Allows for functions to be access controled
* Permissions cannot be changed after a grace period
*/
contract StaticAccessControlled is AccessControlledBase, Ownable {
using SafeMath for uint256;
// ============ State Variables ============
// Timestamp after which no additional access can be granted
uint256 public GRACE_PERIOD_EXPIRATION;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
Ownable()
{
GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod);
}
// ============ Owner-Only State-Changing Functions ============
function grantAccess(
address who
)
external
onlyOwner
{
require(
block.timestamp < GRACE_PERIOD_EXPIRATION,
"StaticAccessControlled#grantAccess: Cannot grant access after grace period"
);
emit AccessGranted(who);
authorized[who] = true;
}
}
// File: contracts/lib/GeneralERC20.sol
/**
* @title GeneralERC20
* @author dYdX
*
* Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so
* that we dont automatically revert when calling non-compliant tokens that have no return value for
* transfer(), transferFrom(), or approve().
*/
interface GeneralERC20 {
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;
function transferFrom(
address from,
address to,
uint256 value
)
external;
function approve(
address spender,
uint256 value
)
external;
}
// File: contracts/lib/TokenInteract.sol
/**
* @title TokenInteract
* @author dYdX
*
* This library contains functions for interacting with ERC20 tokens
*/
library TokenInteract {
function balanceOf(
address token,
address owner
)
internal
view
returns (uint256)
{
return GeneralERC20(token).balanceOf(owner);
}
function allowance(
address token,
address owner,
address spender
)
internal
view
returns (uint256)
{
return GeneralERC20(token).allowance(owner, spender);
}
function approve(
address token,
address spender,
uint256 amount
)
internal
{
GeneralERC20(token).approve(spender, amount);
require(
checkSuccess(),
"TokenInteract#approve: Approval failed"
);
}
function transfer(
address token,
address to,
uint256 amount
)
internal
{
address from = address(this);
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transfer(to, amount);
require(
checkSuccess(),
"TokenInteract#transfer: Transfer failed"
);
}
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transferFrom(from, to, amount);
require(
checkSuccess(),
"TokenInteract#transferFrom: TransferFrom failed"
);
}
// ============ Private Helper-Functions ============
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 32 bytes that are not all-zero.
*/
function checkSuccess(
)
private
pure
returns (bool)
{
uint256 returnValue = 0;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
// check number of bytes returned from last function call
switch returndatasize
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
return returnValue != 0;
}
}
// File: contracts/margin/TokenProxy.sol
/**
* @title TokenProxy
* @author dYdX
*
* Used to transfer tokens between addresses which have set allowance on this contract.
*/
contract TokenProxy is StaticAccessControlled {
using SafeMath for uint256;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{}
// ============ Authorized-Only State Changing Functions ============
/**
* Transfers tokens from an address (that has set allowance on the proxy) to another address.
*
* @param token The address of the ERC20 token
* @param from The address to transfer token from
* @param to The address to transfer tokens to
* @param value The number of tokens to transfer
*/
function transferTokens(
address token,
address from,
address to,
uint256 value
)
external
requiresAuthorization
{
TokenInteract.transferFrom(
token,
from,
to,
value
);
}
// ============ Public Constant Functions ============
/**
* Getter function to get the amount of token that the proxy is able to move for a particular
* address. The minimum of 1) the balance of that address and 2) the allowance given to proxy.
*
* @param who The owner of the tokens
* @param token The address of the ERC20 token
* @return The number of tokens able to be moved by the proxy from the address specified
*/
function available(
address who,
address token
)
external
view
returns (uint256)
{
return Math.min256(
TokenInteract.allowance(token, who, address(this)),
TokenInteract.balanceOf(token, who)
);
}
}
// File: contracts/margin/Vault.sol
/**
* @title Vault
* @author dYdX
*
* Holds and transfers tokens in vaults denominated by id
*
* Vault only supports ERC20 tokens, and will not accept any tokens that require
* a tokenFallback or equivalent function (See ERC223, ERC777, etc.)
*/
contract Vault is StaticAccessControlled
{
using SafeMath for uint256;
// ============ Events ============
event ExcessTokensWithdrawn(
address indexed token,
address indexed to,
address caller
);
// ============ State Variables ============
// Address of the TokenProxy contract. Used for moving tokens.
address public TOKEN_PROXY;
// Map from vault ID to map from token address to amount of that token attributed to the
// particular vault ID.
mapping (bytes32 => mapping (address => uint256)) public balances;
// Map from token address to total amount of that token attributed to some account.
mapping (address => uint256) public totalBalances;
// ============ Constructor ============
constructor(
address proxy,
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{
TOKEN_PROXY = proxy;
}
// ============ Owner-Only State-Changing Functions ============
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY
* will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
uint256 actualBalance = TokenInteract.balanceOf(token, address(this));
uint256 accountedBalance = totalBalances[token];
uint256 withdrawableBalance = actualBalance.sub(accountedBalance);
require(
withdrawableBalance != 0,
"Vault#withdrawExcessToken: Withdrawable token amount must be non-zero"
);
TokenInteract.transfer(token, to, withdrawableBalance);
emit ExcessTokensWithdrawn(token, to, msg.sender);
return withdrawableBalance;
}
// ============ Authorized-Only State-Changing Functions ============
/**
* Transfers tokens from an address (that has approved the proxy) to the vault.
*
* @param id The vault which will receive the tokens
* @param token ERC20 token address
* @param from Address from which the tokens will be taken
* @param amount Number of the token to be sent
*/
function transferToVault(
bytes32 id,
address token,
address from,
uint256 amount
)
external
requiresAuthorization
{
// First send tokens to this contract
TokenProxy(TOKEN_PROXY).transferTokens(
token,
from,
address(this),
amount
);
// Then increment balances
balances[id][token] = balances[id][token].add(amount);
totalBalances[token] = totalBalances[token].add(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
validateBalance(token);
}
/**
* Transfers a certain amount of funds to an address.
*
* @param id The vault from which to send the tokens
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @param amount Number of the token to be sent
*/
function transferFromVault(
bytes32 id,
address token,
address to,
uint256 amount
)
external
requiresAuthorization
{
// Next line also asserts that (balances[id][token] >= amount);
balances[id][token] = balances[id][token].sub(amount);
// Next line also asserts that (totalBalances[token] >= amount);
totalBalances[token] = totalBalances[token].sub(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
// Do the sending
TokenInteract.transfer(token, to, amount); // asserts transfer succeeded
// Final validation
validateBalance(token);
}
// ============ Private Helper-Functions ============
/**
* Verifies that this contract is in control of at least as many tokens as accounted for
*
* @param token Address of ERC20 token
*/
function validateBalance(
address token
)
private
view
{
// The actual balance could be greater than totalBalances[token] because anyone
// can send tokens to the contract's address which cannot be accounted for
assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]);
}
}
// File: contracts/lib/ReentrancyGuard.sol
/**
* @title ReentrancyGuard
* @author dYdX
*
* Optimized version of the well-known ReentrancyGuard contract
*/
contract ReentrancyGuard {
uint256 private _guardCounter = 1;
modifier nonReentrant() {
uint256 localCounter = _guardCounter + 1;
_guardCounter = localCounter;
_;
require(
_guardCounter == localCounter,
"Reentrancy check failure"
);
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/lib/Fraction.sol
/**
* @title Fraction
* @author dYdX
*
* This library contains implementations for fraction structs.
*/
library Fraction {
struct Fraction128 {
uint128 num;
uint128 den;
}
}
// File: contracts/lib/FractionMath.sol
/**
* @title FractionMath
* @author dYdX
*
* This library contains safe math functions for manipulating fractions.
*/
library FractionMath {
using SafeMath for uint256;
using SafeMath for uint128;
/**
* Returns a Fraction128 that is equal to a + b
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (sum)
*/
function add(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 left = a.num.mul(b.den);
uint256 right = b.num.mul(a.den);
uint256 denominator = a.den.mul(b.den);
// if left + right overflows, prevent overflow
if (left + right < left) {
left = left.div(2);
right = right.div(2);
denominator = denominator.div(2);
}
return bound(left.add(right), denominator);
}
/**
* Returns a Fraction128 that is equal to a - (1/2)^d
*
* @param a The Fraction128
* @param d The power of (1/2)
* @return The result
*/
function sub1Over(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.den % d == 0) {
return bound(
a.num.sub(a.den.div(d)),
a.den
);
}
return bound(
a.num.mul(d).sub(a.den),
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a / d
*
* @param a The first Fraction128
* @param d The divisor
* @return The result (quotient)
*/
function div(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.num % d == 0) {
return bound(
a.num.div(d),
a.den
);
}
return bound(
a.num,
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a * b.
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (product)
*/
function mul(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
return bound(
a.num.mul(b.num),
a.den.mul(b.den)
);
}
/**
* Returns a fraction from two uint256's. Fits them into uint128 if necessary.
*
* @param num The numerator
* @param den The denominator
* @return The Fraction128 that matches num/den most closely
*/
/* solium-disable-next-line security/no-assign-params */
function bound(
uint256 num,
uint256 den
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 max = num > den ? num : den;
uint256 first128Bits = (max >> 128);
if (first128Bits != 0) {
first128Bits += 1;
num /= first128Bits;
den /= first128Bits;
}
assert(den != 0); // coverage-enable-line
assert(den < 2**128);
assert(num < 2**128);
return Fraction.Fraction128({
num: uint128(num),
den: uint128(den)
});
}
/**
* Returns an in-memory copy of a Fraction128
*
* @param a The Fraction128 to copy
* @return A copy of the Fraction128
*/
function copy(
Fraction.Fraction128 memory a
)
internal
pure
returns (Fraction.Fraction128 memory)
{
validate(a);
return Fraction.Fraction128({ num: a.num, den: a.den });
}
// ============ Private Helper-Functions ============
/**
* Asserts that a Fraction128 is valid (i.e. the denominator is non-zero)
*
* @param a The Fraction128 to validate
*/
function validate(
Fraction.Fraction128 memory a
)
private
pure
{
assert(a.den != 0); // coverage-enable-line
}
}
// File: contracts/lib/Exponent.sol
/**
* @title Exponent
* @author dYdX
*
* This library contains an implementation for calculating e^X for arbitrary fraction X
*/
library Exponent {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
// 2**128 - 1
uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455;
// Number of precomputed integers, X, for E^((1/2)^X)
uint256 constant public MAX_PRECOMPUTE_PRECISION = 32;
// Number of precomputed integers, X, for E^X
uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32;
// ============ Public Implementation Functions ============
/**
* Returns e^X for any fraction X
*
* @param X The exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function exp(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
require(
precomputePrecision <= MAX_PRECOMPUTE_PRECISION,
"Exponent#exp: Precompute precision over maximum"
);
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
// get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2)
uint256 integerX = uint256(Xcopy.num).div(Xcopy.den);
// if X is less than 1, then just calculate X
if (integerX == 0) {
return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision);
}
// get e^integerX
Fraction.Fraction128 memory expOfInt =
getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS);
while (integerX >= NUM_PRECOMPUTED_INTEGERS) {
expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS));
integerX -= NUM_PRECOMPUTED_INTEGERS;
}
// multiply e^integerX by e^decimalX
Fraction.Fraction128 memory decimalX = Fraction.Fraction128({
num: Xcopy.num % Xcopy.den,
den: Xcopy.den
});
return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt);
}
/**
* Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then
* Maclaurin Series approximation to reduce error.
*
* @param X Exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function expHybrid(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION);
assert(X.num < X.den);
// will also throw if precomputePrecision is larger than the array length in getDenominator
Fraction.Fraction128 memory Xtemp = X.copy();
if (Xtemp.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
uint256 d = 1; // 2^i
for (uint256 i = 1; i <= precomputePrecision; i++) {
d *= 2;
// if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d)
if (d.mul(Xtemp.num) >= Xtemp.den) {
Xtemp = Xtemp.sub1Over(uint128(d));
result = result.mul(getPrecomputedEToTheHalfToThe(i));
}
}
return result.mul(expMaclaurin(Xtemp, maclaurinPrecision));
}
/**
* Returns e^X for any X, using Maclaurin Series approximation
*
* e^X = SUM(X^n / n!) for n >= 0
* e^X = 1 + X/1! + X^2/2! + X^3/3! ...
*
* @param X Exponent
* @param precision Accuracy of Maclaurin terms
* @return e^X
*/
function expMaclaurin(
Fraction.Fraction128 memory X,
uint256 precision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
Fraction.Fraction128 memory Xtemp = ONE();
for (uint256 i = 1; i <= precision; i++) {
Xtemp = Xtemp.mul(Xcopy.div(uint128(i)));
result = result.add(Xtemp);
}
return result;
}
/**
* Returns a fraction roughly equaling E^((1/2)^x) for integer x
*/
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= MAX_PRECOMPUTE_PRECISION);
uint128 denominator = [
125182886983370532117250726298150828301,
206391688497133195273760705512282642279,
265012173823417992016237332255925138361,
300298134811882980317033350418940119802,
319665700530617779809390163992561606014,
329812979126047300897653247035862915816,
335006777809430963166468914297166288162,
337634268532609249517744113622081347950,
338955731696479810470146282672867036734,
339618401537809365075354109784799900812,
339950222128463181389559457827561204959,
340116253979683015278260491021941090650,
340199300311581465057079429423749235412,
340240831081268226777032180141478221816,
340261598367316729254995498374473399540,
340271982485676106947851156443492415142,
340277174663693808406010255284800906112,
340279770782412691177936847400746725466,
340281068849199706686796915841848278311,
340281717884450116236033378667952410919,
340282042402539547492367191008339680733,
340282204661700319870089970029119685699,
340282285791309720262481214385569134454,
340282326356121674011576912006427792656,
340282346638529464274601981200276914173,
340282356779733812753265346086924801364,
340282361850336100329388676752133324799,
340282364385637272451648746721404212564,
340282365653287865596328444437856608255,
340282366287113163939555716675618384724,
340282366604025813553891209601455838559,
340282366762482138471739420386372790954,
340282366841710300958333641874363209044
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
/**
* Returns a fraction roughly equaling E^(x) for integer x
*/
function getPrecomputedEToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= NUM_PRECOMPUTED_INTEGERS);
uint128 denominator = [
340282366920938463463374607431768211455,
125182886983370532117250726298150828301,
46052210507670172419625860892627118820,
16941661466271327126146327822211253888,
6232488952727653950957829210887653621,
2292804553036637136093891217529878878,
843475657686456657683449904934172134,
310297353591408453462393329342695980,
114152017036184782947077973323212575,
41994180235864621538772677139808695,
15448795557622704876497742989562086,
5683294276510101335127414470015662,
2090767122455392675095471286328463,
769150240628514374138961856925097,
282954560699298259527814398449860,
104093165666968799599694528310221,
38293735615330848145349245349513,
14087478058534870382224480725096,
5182493555688763339001418388912,
1906532833141383353974257736699,
701374233231058797338605168652,
258021160973090761055471434334,
94920680509187392077350434438,
34919366901332874995585576427,
12846117181722897538509298435,
4725822410035083116489797150,
1738532907279185132707372378,
639570514388029575350057932,
235284843422800231081973821,
86556456714490055457751527,
31842340925906738090071268,
11714142585413118080082437,
4309392228124372433711936
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
// ============ Private Helper-Functions ============
function ONE()
private
pure
returns (Fraction.Fraction128 memory)
{
return Fraction.Fraction128({ num: 1, den: 1 });
}
}
// File: contracts/lib/MathHelpers.sol
/**
* @title MathHelpers
* @author dYdX
*
* This library helps with common math functions in Solidity
*/
library MathHelpers {
using SafeMath for uint256;
/**
* Calculates partial value given a numerator and denominator.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return target * numerator / denominator
*/
function getPartialAmount(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return numerator.mul(target).div(denominator);
}
/**
* Calculates partial value given a numerator and denominator, rounded up.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return Rounded-up result of target * numerator / denominator
*/
function getPartialAmountRoundedUp(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return divisionRoundedUp(numerator.mul(target), denominator);
}
/**
* Calculates division given a numerator and denominator, rounded up.
*
* @param numerator Numerator.
* @param denominator Denominator.
* @return Rounded-up result of numerator / denominator
*/
function divisionRoundedUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
assert(denominator != 0); // coverage-enable-line
if (numerator == 0) {
return 0;
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint256(
)
internal
pure
returns (uint256)
{
return 2 ** 256 - 1;
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint32(
)
internal
pure
returns (uint32)
{
return 2 ** 32 - 1;
}
/**
* Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0
*
* @param n The uint256 to get the number of bits in
* @return The number of bits in n
*/
function getNumBits(
uint256 n
)
internal
pure
returns (uint256)
{
uint256 first = 0;
uint256 last = 256;
while (first < last) {
uint256 check = (first + last) / 2;
if ((n >> check) == 0) {
last = check;
} else {
first = check + 1;
}
}
assert(first <= 256);
return first;
}
}
// File: contracts/margin/impl/InterestImpl.sol
/**
* @title InterestImpl
* @author dYdX
*
* A library that calculates continuously compounded interest for principal, time period, and
* interest rate.
*/
library InterestImpl {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11;
uint256 constant DEFAULT_MACLAURIN_PRECISION = 5;
uint256 constant MAXIMUM_EXPONENT = 80;
uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613;
// ============ Public Implementation Functions ============
/**
* Returns total tokens owed after accruing interest. Continuously compounding and accurate to
* roughly 10^18 decimal places. Continuously compounding interest follows the formula:
* I = P * e^(R*T)
*
* @param principal Principal of the interest calculation
* @param interestRate Annual nominal interest percentage times 10**6.
* (example: 5% = 5e6)
* @param secondsOfInterest Number of seconds that interest has been accruing
* @return Total amount of tokens owed. Greater than tokenAmount.
*/
function getCompoundedInterest(
uint256 principal,
uint256 interestRate,
uint256 secondsOfInterest
)
public
pure
returns (uint256)
{
uint256 numerator = interestRate.mul(secondsOfInterest);
uint128 denominator = (10**8) * (365 * 1 days);
// interestRate and secondsOfInterest should both be uint32
assert(numerator < 2**128);
// fraction representing (Rate * Time)
Fraction.Fraction128 memory rt = Fraction.Fraction128({
num: uint128(numerator),
den: denominator
});
// calculate e^(RT)
Fraction.Fraction128 memory eToRT;
if (numerator.div(denominator) >= MAXIMUM_EXPONENT) {
// degenerate case: cap calculation
eToRT = Fraction.Fraction128({
num: E_TO_MAXIUMUM_EXPONENT,
den: 1
});
} else {
// normal case: calculate e^(RT)
eToRT = Exponent.exp(
rt,
DEFAULT_PRECOMPUTE_PRECISION,
DEFAULT_MACLAURIN_PRECISION
);
}
// e^X for positive X should be greater-than or equal to 1
assert(eToRT.num >= eToRT.den);
return safeMultiplyUint256ByFraction(principal, eToRT);
}
// ============ Private Helper-Functions ============
/**
* Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator
* and denominator of f are less than 2**128.
*/
function safeMultiplyUint256ByFraction(
uint256 n,
Fraction.Fraction128 memory f
)
private
pure
returns (uint256)
{
uint256 term1 = n.div(2 ** 128); // first 128 bits
uint256 term2 = n % (2 ** 128); // second 128 bits
// uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f
if (term1 > 0) {
term1 = term1.mul(f.num);
uint256 numBits = MathHelpers.getNumBits(term1);
// reduce rounding error by shifting all the way to the left before dividing
term1 = MathHelpers.divisionRoundedUp(
term1 << (uint256(256).sub(numBits)),
f.den);
// continue shifting or reduce shifting to get the right number
if (numBits > 128) {
term1 = term1 << (numBits.sub(128));
} else if (numBits < 128) {
term1 = term1 >> (uint256(128).sub(numBits));
}
}
// calculates term2 = term2 * f
term2 = MathHelpers.getPartialAmountRoundedUp(
f.num,
f.den,
term2
);
return term1.add(term2);
}
}
// File: contracts/margin/impl/MarginState.sol
/**
* @title MarginState
* @author dYdX
*
* Contains state for the Margin contract. Also used by libraries that implement Margin functions.
*/
library MarginState {
struct State {
// Address of the Vault contract
address VAULT;
// Address of the TokenProxy contract
address TOKEN_PROXY;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been filled.
mapping (bytes32 => uint256) loanFills;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been canceled.
mapping (bytes32 => uint256) loanCancels;
// Mapping from positionId -> Position, which stores all the open margin positions.
mapping (bytes32 => MarginCommon.Position) positions;
// Mapping from positionId -> bool, which stores whether the position has previously been
// open, but is now closed.
mapping (bytes32 => bool) closedPositions;
// Mapping from positionId -> uint256, which stores the total amount of owedToken that has
// ever been repaid to the lender for each position. Does not reset.
mapping (bytes32 => uint256) totalOwedTokenRepaidToLender;
}
}
// File: contracts/margin/interfaces/lender/LoanOwner.sol
/**
* @title LoanOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a loan sell via the
* transferLoan function or the atomic-assign to the "owner" field in a loan offering.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/PositionOwner.sol
/**
* @title PositionOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PositionOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a position via the
* transferPosition function or the atomic-assign to the "owner" field when opening a position.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receivePositionOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/TransferInternal.sol
/**
* @title TransferInternal
* @author dYdX
*
* This library contains the implementation for transferring ownership of loans and positions.
*/
library TransferInternal {
// ============ Events ============
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a postion was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
// ============ Internal Implementation Functions ============
/**
* Returns either the address of the new loan owner, or the address to which they wish to
* pass ownership of the loan. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the loan
* @param newOwner The intended owner of the loan
* @return The address that the intended owner wishes to assign the loan to (may be
* the same as the intended owner).
*/
function grantLoanOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit LoanTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantLoanOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantLoanOwnership: New owner did not consent to owning loan"
);
return newOwner;
}
/**
* Returns either the address of the new position owner, or the address to which they wish to
* pass ownership of the position. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the position
* @param newOwner The intended owner of the position
* @return The address that the intended owner wishes to assign the position to (may
* be the same as the intended owner).
*/
function grantPositionOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit PositionTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantPositionOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantPositionOwnership: New owner did not consent to owning position"
);
return newOwner;
}
}
// File: contracts/lib/TimestampHelper.sol
/**
* @title TimestampHelper
* @author dYdX
*
* Helper to get block timestamps in other formats
*/
library TimestampHelper {
function getBlockTimestamp32()
internal
view
returns (uint32)
{
// Should not still be in-use in the year 2106
assert(uint256(uint32(block.timestamp)) == block.timestamp);
assert(block.timestamp > 0);
return uint32(block.timestamp);
}
}
// File: contracts/margin/impl/MarginCommon.sol
/**
* @title MarginCommon
* @author dYdX
*
* This library contains common functions for implementations of public facing Margin functions
*/
library MarginCommon {
using SafeMath for uint256;
// ============ Structs ============
struct Position {
address owedToken; // Immutable
address heldToken; // Immutable
address lender;
address owner;
uint256 principal;
uint256 requiredDeposit;
uint32 callTimeLimit; // Immutable
uint32 startTimestamp; // Immutable, cannot be 0
uint32 callTimestamp;
uint32 maxDuration; // Immutable
uint32 interestRate; // Immutable
uint32 interestPeriod; // Immutable
}
struct LoanOffering {
address owedToken;
address heldToken;
address payer;
address owner;
address taker;
address positionOwner;
address feeRecipient;
address lenderFeeToken;
address takerFeeToken;
LoanRates rates;
uint256 expirationTimestamp;
uint32 callTimeLimit;
uint32 maxDuration;
uint256 salt;
bytes32 loanHash;
bytes signature;
}
struct LoanRates {
uint256 maxAmount;
uint256 minAmount;
uint256 minHeldToken;
uint256 lenderFee;
uint256 takerFee;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Internal Implementation Functions ============
function storeNewPosition(
MarginState.State storage state,
bytes32 positionId,
Position memory position,
address loanPayer
)
internal
{
assert(!positionHasExisted(state, positionId));
assert(position.owedToken != address(0));
assert(position.heldToken != address(0));
assert(position.owedToken != position.heldToken);
assert(position.owner != address(0));
assert(position.lender != address(0));
assert(position.maxDuration != 0);
assert(position.interestPeriod <= position.maxDuration);
assert(position.callTimestamp == 0);
assert(position.requiredDeposit == 0);
state.positions[positionId].owedToken = position.owedToken;
state.positions[positionId].heldToken = position.heldToken;
state.positions[positionId].principal = position.principal;
state.positions[positionId].callTimeLimit = position.callTimeLimit;
state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32();
state.positions[positionId].maxDuration = position.maxDuration;
state.positions[positionId].interestRate = position.interestRate;
state.positions[positionId].interestPeriod = position.interestPeriod;
state.positions[positionId].owner = TransferInternal.grantPositionOwnership(
positionId,
(position.owner != msg.sender) ? msg.sender : address(0),
position.owner
);
state.positions[positionId].lender = TransferInternal.grantLoanOwnership(
positionId,
(position.lender != loanPayer) ? loanPayer : address(0),
position.lender
);
}
function getPositionIdFromNonce(
uint256 nonce
)
internal
view
returns (bytes32)
{
return keccak256(abi.encodePacked(msg.sender, nonce));
}
function getUnavailableLoanOfferingAmountImpl(
MarginState.State storage state,
bytes32 loanHash
)
internal
view
returns (uint256)
{
return state.loanFills[loanHash].add(state.loanCancels[loanHash]);
}
function cleanupPosition(
MarginState.State storage state,
bytes32 positionId
)
internal
{
delete state.positions[positionId];
state.closedPositions[positionId] = true;
}
function calculateOwedAmount(
Position storage position,
uint256 closeAmount,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
closeAmount,
position.interestRate,
timeElapsed
);
}
/**
* Calculates time elapsed rounded up to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsed(
Position storage position,
uint256 timestamp
)
internal
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round up to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function calculateLenderAmountForIncreasePosition(
Position storage position,
uint256 principalToAdd,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
principalToAdd,
position.interestRate,
timeElapsed
);
}
function getLoanOfferingHash(
LoanOffering loanOffering
)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
address(this),
loanOffering.owedToken,
loanOffering.heldToken,
loanOffering.payer,
loanOffering.owner,
loanOffering.taker,
loanOffering.positionOwner,
loanOffering.feeRecipient,
loanOffering.lenderFeeToken,
loanOffering.takerFeeToken,
getValuesHash(loanOffering)
)
);
}
function getPositionBalanceImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns(uint256)
{
return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken);
}
function containsPositionImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return state.positions[positionId].startTimestamp != 0;
}
function positionHasExisted(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return containsPositionImpl(state, positionId) || state.closedPositions[positionId];
}
function getPositionFromStorage(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (Position storage)
{
Position storage position = state.positions[positionId];
require(
position.startTimestamp != 0,
"MarginCommon#getPositionFromStorage: The position does not exist"
);
return position;
}
// ============ Private Helper-Functions ============
/**
* Calculates time elapsed rounded down to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsedForNewLender(
Position storage position,
uint256 timestamp
)
private
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round down to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = elapsed.div(period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function getValuesHash(
LoanOffering loanOffering
)
private
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
loanOffering.rates.maxAmount,
loanOffering.rates.minAmount,
loanOffering.rates.minHeldToken,
loanOffering.rates.lenderFee,
loanOffering.rates.takerFee,
loanOffering.expirationTimestamp,
loanOffering.salt,
loanOffering.callTimeLimit,
loanOffering.maxDuration,
loanOffering.rates.interestRate,
loanOffering.rates.interestPeriod
)
);
}
}
// File: contracts/margin/interfaces/PayoutRecipient.sol
/**
* @title PayoutRecipient
* @author dYdX
*
* Interface that smart contracts must implement in order to be the payoutRecipient in a
* closePosition transaction.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PayoutRecipient {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive payout from being the payoutRecipient
* in a closePosition transaction. May redistribute any payout as necessary. Throws on error.
*
* @param positionId Unique ID of the position
* @param closeAmount Amount of the position that was closed
* @param closer Address of the account or contract that closed the position
* @param positionOwner Address of the owner of the position
* @param heldToken Address of the ERC20 heldToken
* @param payout Number of tokens received from the payout
* @param totalHeldToken Total amount of heldToken removed from vault during close
* @param payoutInHeldToken True if payout is in heldToken, false if in owedToken
* @return True if approved by the receiver
*/
function receiveClosePositionPayout(
bytes32 positionId,
uint256 closeAmount,
address closer,
address positionOwner,
address heldToken,
uint256 payout,
uint256 totalHeldToken,
bool payoutInHeldToken
)
external
/* onlyMargin */
returns (bool);
}
// File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol
/**
* @title CloseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CloseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* closeWithoutCounterparty().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at most) the specified amount of the loan was
* successfully closed.
*
* @param closer Address of the caller of closeWithoutCounterparty()
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the loan to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeLoanOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol
/**
* @title ClosePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a position
* owned by the smart contract, allowing more complex logic to control positions.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ClosePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call closePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at-most) the specified amount of the position
* was successfully closed.
*
* @param closer Address of the caller of the closePosition() function
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the position to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/impl/ClosePositionShared.sol
/**
* @title ClosePositionShared
* @author dYdX
*
* This library contains shared functionality between ClosePositionImpl and
* CloseWithoutCounterpartyImpl
*/
library ClosePositionShared {
using SafeMath for uint256;
// ============ Structs ============
struct CloseTx {
bytes32 positionId;
uint256 originalPrincipal;
uint256 closeAmount;
uint256 owedTokenOwed;
uint256 startingHeldTokenBalance;
uint256 availableHeldToken;
address payoutRecipient;
address owedToken;
address heldToken;
address positionOwner;
address positionLender;
address exchangeWrapper;
bool payoutInHeldToken;
}
// ============ Internal Implementation Functions ============
function closePositionStateUpdate(
MarginState.State storage state,
CloseTx memory transaction
)
internal
{
// Delete the position, or just decrease the principal
if (transaction.closeAmount == transaction.originalPrincipal) {
MarginCommon.cleanupPosition(state, transaction.positionId);
} else {
assert(
transaction.originalPrincipal == state.positions[transaction.positionId].principal
);
state.positions[transaction.positionId].principal =
transaction.originalPrincipal.sub(transaction.closeAmount);
}
}
function sendTokensToPayoutRecipient(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
)
internal
returns (uint256)
{
uint256 payout;
if (transaction.payoutInHeldToken) {
// Send remaining heldToken to payoutRecipient
payout = transaction.availableHeldToken.sub(buybackCostInHeldToken);
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.payoutRecipient,
payout
);
} else {
assert(transaction.exchangeWrapper != address(0));
payout = receivedOwedToken.sub(transaction.owedTokenOwed);
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.payoutRecipient,
payout
);
}
if (AddressUtils.isContract(transaction.payoutRecipient)) {
require(
PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout(
transaction.positionId,
transaction.closeAmount,
msg.sender,
transaction.positionOwner,
transaction.heldToken,
payout,
transaction.availableHeldToken,
transaction.payoutInHeldToken
),
"ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent"
);
}
// The ending heldToken balance of the vault should be the starting heldToken balance
// minus the available heldToken amount
assert(
MarginCommon.getPositionBalanceImpl(state, transaction.positionId)
== transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken)
);
return payout;
}
function createCloseTx(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
internal
returns (CloseTx memory)
{
// Validate
require(
payoutRecipient != address(0),
"ClosePositionShared#createCloseTx: Payout recipient cannot be 0"
);
require(
requestedAmount > 0,
"ClosePositionShared#createCloseTx: Requested close amount cannot be 0"
);
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 closeAmount = getApprovedAmount(
position,
positionId,
requestedAmount,
payoutRecipient,
isWithoutCounterparty
);
return parseCloseTx(
state,
position,
positionId,
closeAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
isWithoutCounterparty
);
}
// ============ Private Helper-Functions ============
function getApprovedAmount(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
bool requireLenderApproval
)
private
returns (uint256)
{
// Ensure enough principal
uint256 allowedAmount = Math.min256(requestedAmount, position.principal);
// Ensure owner consent
allowedAmount = closePositionOnBehalfOfRecurse(
position.owner,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
// Ensure lender consent
if (requireLenderApproval) {
allowedAmount = closeLoanOnBehalfOfRecurse(
position.lender,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
}
assert(allowedAmount > 0);
assert(allowedAmount <= position.principal);
assert(allowedAmount <= requestedAmount);
return allowedAmount;
}
function closePositionOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = ClosePositionDelegator(contractAddr).closeOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closePositionRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closePositionOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
function closeLoanOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closeLoanOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
// ============ Parsing Functions ============
function parseCloseTx(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 closeAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
private
view
returns (CloseTx memory)
{
uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
uint256 availableHeldToken = MathHelpers.getPartialAmount(
closeAmount,
position.principal,
startingHeldTokenBalance
);
uint256 owedTokenOwed = 0;
if (!isWithoutCounterparty) {
owedTokenOwed = MarginCommon.calculateOwedAmount(
position,
closeAmount,
block.timestamp
);
}
return CloseTx({
positionId: positionId,
originalPrincipal: position.principal,
closeAmount: closeAmount,
owedTokenOwed: owedTokenOwed,
startingHeldTokenBalance: startingHeldTokenBalance,
availableHeldToken: availableHeldToken,
payoutRecipient: payoutRecipient,
owedToken: position.owedToken,
heldToken: position.heldToken,
positionOwner: position.owner,
positionLender: position.lender,
exchangeWrapper: exchangeWrapper,
payoutInHeldToken: payoutInHeldToken
});
}
}
// File: contracts/margin/interfaces/ExchangeWrapper.sol
/**
* @title ExchangeWrapper
* @author dYdX
*
* Contract interface that Exchange Wrapper smart contracts must implement in order to interface
* with other smart contracts through a common interface.
*/
interface ExchangeWrapper {
// ============ Public Functions ============
/**
* Exchange some amount of takerToken for makerToken.
*
* @param tradeOriginator Address of the initiator of the trade (however, this value
* cannot always be trusted as it is set at the discretion of the
* msg.sender)
* @param receiver Address to set allowance on once the trade has completed
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param requestedFillAmount Amount of takerToken being paid
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return The amount of makerToken received
*/
function exchange(
address tradeOriginator,
address receiver,
address makerToken,
address takerToken,
uint256 requestedFillAmount,
bytes orderData
)
external
returns (uint256);
/**
* Get amount of takerToken required to buy a certain amount of makerToken for a given trade.
* Should match the takerToken amount used in exchangeForAmount. If the order cannot provide
* exactly desiredMakerToken, then it must return the price to buy the minimum amount greater
* than desiredMakerToken
*
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param desiredMakerToken Amount of makerToken requested
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return Amount of takerToken the needed to complete the transaction
*/
function getExchangeCost(
address makerToken,
address takerToken,
uint256 desiredMakerToken,
bytes orderData
)
external
view
returns (uint256);
}
// File: contracts/margin/impl/ClosePositionImpl.sol
/**
* @title ClosePositionImpl
* @author dYdX
*
* This library contains the implementation for the closePosition function of Margin
*/
library ClosePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closePositionImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes memory orderData
)
public
returns (uint256, uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
false
);
(
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
) = returnOwedTokensToLender(
state,
transaction,
orderData
);
uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
buybackCostInHeldToken,
receivedOwedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnClose(
transaction,
buybackCostInHeldToken,
payout
);
return (
transaction.closeAmount,
payout,
transaction.owedTokenOwed
);
}
// ============ Private Helper-Functions ============
function returnOwedTokensToLender(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
uint256 buybackCostInHeldToken = 0;
uint256 receivedOwedToken = 0;
uint256 lenderOwedToken = transaction.owedTokenOwed;
// Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly
// from msg.sender
if (transaction.exchangeWrapper == address(0)) {
require(
transaction.payoutInHeldToken,
"ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken"
);
// No DEX Order; send owedTokens directly from the closer to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
msg.sender,
transaction.positionLender,
lenderOwedToken
);
} else {
// Buy back owedTokens using DEX Order and send to lender
(buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken(
state,
transaction,
orderData
);
// If no owedToken needed for payout: give lender all owedToken, even if more than owed
if (transaction.payoutInHeldToken) {
assert(receivedOwedToken >= lenderOwedToken);
lenderOwedToken = receivedOwedToken;
}
// Transfer owedToken from the exchange wrapper to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.positionLender,
lenderOwedToken
);
}
state.totalOwedTokenRepaidToLender[transaction.positionId] =
state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken);
return (buybackCostInHeldToken, receivedOwedToken);
}
function buyBackOwedToken(
MarginState.State storage state,
ClosePositionShared.CloseTx transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
// Ask the exchange wrapper the cost in heldToken to buy back the close
// amount of owedToken
uint256 buybackCostInHeldToken;
if (transaction.payoutInHeldToken) {
buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper)
.getExchangeCost(
transaction.owedToken,
transaction.heldToken,
transaction.owedTokenOwed,
orderData
);
// Require enough available heldToken to pay for the buyback
require(
buybackCostInHeldToken <= transaction.availableHeldToken,
"ClosePositionImpl#buyBackOwedToken: Not enough available heldToken"
);
} else {
buybackCostInHeldToken = transaction.availableHeldToken;
}
// Send the requisite heldToken to do the buyback from vault to exchange wrapper
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.exchangeWrapper,
buybackCostInHeldToken
);
// Trade the heldToken for the owedToken
uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.owedToken,
transaction.heldToken,
buybackCostInHeldToken,
orderData
);
require(
receivedOwedToken >= transaction.owedTokenOwed,
"ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken"
);
return (buybackCostInHeldToken, receivedOwedToken);
}
function logEventOnClose(
ClosePositionShared.CloseTx transaction,
uint256 buybackCostInHeldToken,
uint256 payout
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
transaction.owedTokenOwed,
payout,
buybackCostInHeldToken,
transaction.payoutInHeldToken
);
}
}
// File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol
/**
* @title CloseWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the closeWithoutCounterpartyImpl function of
* Margin
*/
library CloseWithoutCounterpartyImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closeWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
public
returns (uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
true
);
uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
0, // No buyback cost
0 // Did not receive any owedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnCloseWithoutCounterparty(transaction);
return (
transaction.closeAmount,
heldTokenPayout
);
}
// ============ Private Helper-Functions ============
function logEventOnCloseWithoutCounterparty(
ClosePositionShared.CloseTx transaction
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
0,
transaction.availableHeldToken,
0,
true
);
}
}
// File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol
/**
* @title DepositCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses deposit heldTokens
* into a position owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface DepositCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call depositCollateral().
*
* @param depositor Address of the caller of the depositCollateral() function
* @param positionId Unique ID of the position
* @param amount Requested deposit amount
* @return This address to accept, a different address to ask that contract
*/
function depositCollateralOnBehalfOf(
address depositor,
bytes32 positionId,
uint256 amount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/DepositCollateralImpl.sol
/**
* @title DepositCollateralImpl
* @author dYdX
*
* This library contains the implementation for the deposit function of Margin
*/
library DepositCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
// ============ Public Implementation Functions ============
function depositCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 depositAmount
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
depositAmount > 0,
"DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0"
);
// Ensure owner consent
depositCollateralOnBehalfOfRecurse(
position.owner,
msg.sender,
positionId,
depositAmount
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
depositAmount
);
// cancel margin call if applicable
bool marginCallCanceled = false;
uint256 requiredDeposit = position.requiredDeposit;
if (position.callTimestamp > 0 && requiredDeposit > 0) {
if (depositAmount >= requiredDeposit) {
position.requiredDeposit = 0;
position.callTimestamp = 0;
marginCallCanceled = true;
} else {
position.requiredDeposit = position.requiredDeposit.sub(depositAmount);
}
}
emit AdditionalCollateralDeposited(
positionId,
depositAmount,
msg.sender
);
if (marginCallCanceled) {
emit MarginCallCanceled(
positionId,
position.lender,
msg.sender,
depositAmount
);
}
}
// ============ Private Helper-Functions ============
function depositCollateralOnBehalfOfRecurse(
address contractAddr,
address depositor,
bytes32 positionId,
uint256 amount
)
private
{
// no need to ask for permission
if (depositor == contractAddr) {
return;
}
address newContractAddr =
DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf(
depositor,
positionId,
amount
);
// if not equal, recurse
if (newContractAddr != contractAddr) {
depositCollateralOnBehalfOfRecurse(
newContractAddr,
depositor,
positionId,
amount
);
}
}
}
// File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol
/**
* @title ForceRecoverCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses
* forceRecoverCollateral() a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ForceRecoverCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* NOTE: If not returning zero address (or not reverting), this contract must assume that Margin
* will either revert the entire transaction or that the collateral was forcibly recovered.
*
* @param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address recoverer,
bytes32 positionId,
address recipient
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/ForceRecoverCollateralImpl.sol
/**
* @title ForceRecoverCollateralImpl
* @author dYdX
*
* This library contains the implementation for the forceRecoverCollateral function of Margin
*/
library ForceRecoverCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
// ============ Public Implementation Functions ============
function forceRecoverCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
address recipient
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Can only force recover after either:
// 1) The loan was called and the call period has elapsed
// 2) The maxDuration of the position has elapsed
require( /* solium-disable-next-line */
(
position.callTimestamp > 0
&& block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit)
) || (
block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration)
),
"ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet"
);
// Ensure lender consent
forceRecoverCollateralOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
recipient
);
// Send the tokens
uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId);
Vault(state.VAULT).transferFromVault(
positionId,
position.heldToken,
recipient,
heldTokenRecovered
);
// Delete the position
// NOTE: Since position is a storage pointer, this will also set all fields on
// the position variable to 0
MarginCommon.cleanupPosition(
state,
positionId
);
// Log an event
emit CollateralForceRecovered(
positionId,
recipient,
heldTokenRecovered
);
return heldTokenRecovered;
}
// ============ Private Helper-Functions ============
function forceRecoverCollateralOnBehalfOfRecurse(
address contractAddr,
address recoverer,
bytes32 positionId,
address recipient
)
private
{
// no need to ask for permission
if (recoverer == contractAddr) {
return;
}
address newContractAddr =
ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf(
recoverer,
positionId,
recipient
);
if (newContractAddr != contractAddr) {
forceRecoverCollateralOnBehalfOfRecurse(
newContractAddr,
recoverer,
positionId,
recipient
);
}
}
}
// File: contracts/lib/TypedSignature.sol
/**
* @title TypedSignature
* @author dYdX
*
* Allows for ecrecovery of signed hashes with three different prepended messages:
* 1) ""
* 2) "\x19Ethereum Signed Message:\n32"
* 3) "\x19Ethereum Signed Message:\n\x20"
*/
library TypedSignature {
// Solidity does not offer guarantees about enum values, so we define them explicitly
uint8 private constant SIGTYPE_INVALID = 0;
uint8 private constant SIGTYPE_ECRECOVER_DEC = 1;
uint8 private constant SIGTYPE_ECRECOVER_HEX = 2;
uint8 private constant SIGTYPE_UNSUPPORTED = 3;
// prepended message with the length of the signed hash in hexadecimal
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
// prepended message with the length of the signed hash in decimal
bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32";
/**
* Gives the address of the signer of a hash. Allows for three common prepended strings.
*
* @param hash Hash that was signed (does not include prepended message)
* @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s}
* @return address of the signer of the hash
*/
function recover(
bytes32 hash,
bytes signatureWithType
)
internal
pure
returns (address)
{
require(
signatureWithType.length == 66,
"SignatureValidator#validateSignature: invalid signature length"
);
uint8 sigType = uint8(signatureWithType[0]);
require(
sigType > uint8(SIGTYPE_INVALID),
"SignatureValidator#validateSignature: invalid signature type"
);
require(
sigType < uint8(SIGTYPE_UNSUPPORTED),
"SignatureValidator#validateSignature: unsupported signature type"
);
uint8 v = uint8(signatureWithType[1]);
bytes32 r;
bytes32 s;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
r := mload(add(signatureWithType, 34))
s := mload(add(signatureWithType, 66))
}
bytes32 signedHash;
if (sigType == SIGTYPE_ECRECOVER_DEC) {
signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash));
} else {
assert(sigType == SIGTYPE_ECRECOVER_HEX);
signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash));
}
return ecrecover(
signedHash,
v,
r,
s
);
}
}
// File: contracts/margin/interfaces/LoanOfferingVerifier.sol
/**
* @title LoanOfferingVerifier
* @author dYdX
*
* Interface that smart contracts must implement to be able to make off-chain generated
* loan offerings.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOfferingVerifier {
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* If true is returned, and no errors are thrown by the Margin contract, the loan will have
* occurred. This means that verifyLoanOffering can also be used to update internal contract
* state on a loan.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan positionOwner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes; may or may not be an ECDSA signature
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/BorrowShared.sol
/**
* @title BorrowShared
* @author dYdX
*
* This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl.
* Both use a Loan Offering and a DEX Order to open or increase a position.
*/
library BorrowShared {
using SafeMath for uint256;
// ============ Structs ============
struct Tx {
bytes32 positionId;
address owner;
uint256 principal;
uint256 lenderAmount;
MarginCommon.LoanOffering loanOffering;
address exchangeWrapper;
bool depositInHeldToken;
uint256 depositAmount;
uint256 collateralAmount;
uint256 heldTokenFromSell;
}
// ============ Internal Implementation Functions ============
/**
* Validate the transaction before exchanging heldToken for owedToken
*/
function validateTxPreSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
assert(transaction.lenderAmount >= transaction.principal);
require(
transaction.principal > 0,
"BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed"
);
// If the taker is 0x0 then any address can take it. Otherwise only the taker can use it.
if (transaction.loanOffering.taker != address(0)) {
require(
msg.sender == transaction.loanOffering.taker,
"BorrowShared#validateTxPreSell: Invalid loan offering taker"
);
}
// If the positionOwner is 0x0 then any address can be set as the position owner.
// Otherwise only the specified positionOwner can be set as the position owner.
if (transaction.loanOffering.positionOwner != address(0)) {
require(
transaction.owner == transaction.loanOffering.positionOwner,
"BorrowShared#validateTxPreSell: Invalid position owner"
);
}
// Require the loan offering to be approved by the payer
if (AddressUtils.isContract(transaction.loanOffering.payer)) {
getConsentFromSmartContractLender(transaction);
} else {
require(
transaction.loanOffering.payer == TypedSignature.recover(
transaction.loanOffering.loanHash,
transaction.loanOffering.signature
),
"BorrowShared#validateTxPreSell: Invalid loan offering signature"
);
}
// Validate the amount is <= than max and >= min
uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl(
state,
transaction.loanOffering.loanHash
);
require(
transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount,
"BorrowShared#validateTxPreSell: Loan offering does not have enough available"
);
require(
transaction.lenderAmount >= transaction.loanOffering.rates.minAmount,
"BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount"
);
require(
transaction.loanOffering.owedToken != transaction.loanOffering.heldToken,
"BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken"
);
require(
transaction.owner != address(0),
"BorrowShared#validateTxPreSell: Position owner cannot be 0"
);
require(
transaction.loanOffering.owner != address(0),
"BorrowShared#validateTxPreSell: Loan owner cannot be 0"
);
require(
transaction.loanOffering.expirationTimestamp > block.timestamp,
"BorrowShared#validateTxPreSell: Loan offering is expired"
);
require(
transaction.loanOffering.maxDuration > 0,
"BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration"
);
require(
transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration,
"BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration"
);
// The minimum heldToken is validated after executing the sell
// Position and loan ownership is validated in TransferInternal
}
/**
* Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store
* how much of the loan was used.
*/
function doPostSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
validateTxPostSell(transaction);
// Transfer feeTokens from trader and lender
transferLoanFees(state, transaction);
// Update global amounts for the loan
state.loanFills[transaction.loanOffering.loanHash] =
state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount);
}
/**
* Sells the owedToken from the lender (and from the deposit if in owedToken) using the
* exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for
* maxHeldTokenToBuy of heldTokens at most.
*/
function doSell(
MarginState.State storage state,
Tx transaction,
bytes orderData,
uint256 maxHeldTokenToBuy
)
internal
returns (uint256)
{
// Move owedTokens from lender to exchange wrapper
pullOwedTokensFromLender(state, transaction);
// Sell just the lender's owedToken (if trader deposit is in heldToken)
// Otherwise sell both the lender's owedToken and the trader's deposit in owedToken
uint256 sellAmount = transaction.depositInHeldToken ?
transaction.lenderAmount :
transaction.lenderAmount.add(transaction.depositAmount);
// Do the trade, taking only the maxHeldTokenToBuy if more is returned
uint256 heldTokenFromSell = Math.min256(
maxHeldTokenToBuy,
ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
sellAmount,
orderData
)
);
// Move the tokens to the vault
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
transaction.exchangeWrapper,
heldTokenFromSell
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell);
return heldTokenFromSell;
}
/**
* Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can
* be sold for heldToken.
*/
function doDepositOwedToken(
MarginState.State storage state,
Tx transaction
)
internal
{
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
msg.sender,
transaction.exchangeWrapper,
transaction.depositAmount
);
}
/**
* Take the heldToken deposit from the trader and move it to the vault.
*/
function doDepositHeldToken(
MarginState.State storage state,
Tx transaction
)
internal
{
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
msg.sender,
transaction.depositAmount
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount);
}
// ============ Private Helper-Functions ============
function validateTxPostSell(
Tx transaction
)
private
pure
{
uint256 expectedCollateral = transaction.depositInHeldToken ?
transaction.heldTokenFromSell.add(transaction.depositAmount) :
transaction.heldTokenFromSell;
assert(transaction.collateralAmount == expectedCollateral);
uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minHeldToken
);
require(
transaction.collateralAmount >= loanOfferingMinimumHeldToken,
"BorrowShared#validateTxPostSell: Loan offering minimum held token not met"
);
}
function getConsentFromSmartContractLender(
Tx transaction
)
private
{
verifyLoanOfferingRecurse(
transaction.loanOffering.payer,
getLoanOfferingAddresses(transaction),
getLoanOfferingValues256(transaction),
getLoanOfferingValues32(transaction),
transaction.positionId,
transaction.loanOffering.signature
);
}
function verifyLoanOfferingRecurse(
address contractAddr,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
private
{
address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering(
addresses,
values256,
values32,
positionId,
signature
);
if (newContractAddr != contractAddr) {
verifyLoanOfferingRecurse(
newContractAddr,
addresses,
values256,
values32,
positionId,
signature
);
}
}
function pullOwedTokensFromLender(
MarginState.State storage state,
Tx transaction
)
private
{
// Transfer owedToken to the exchange wrapper
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
transaction.loanOffering.payer,
transaction.exchangeWrapper,
transaction.lenderAmount
);
}
function transferLoanFees(
MarginState.State storage state,
Tx transaction
)
private
{
// 0 fee address indicates no fees
if (transaction.loanOffering.feeRecipient == address(0)) {
return;
}
TokenProxy proxy = TokenProxy(state.TOKEN_PROXY);
uint256 lenderFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.lenderFee
);
uint256 takerFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.takerFee
);
if (lenderFee > 0) {
proxy.transferTokens(
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.payer,
transaction.loanOffering.feeRecipient,
lenderFee
);
}
if (takerFee > 0) {
proxy.transferTokens(
transaction.loanOffering.takerFeeToken,
msg.sender,
transaction.loanOffering.feeRecipient,
takerFee
);
}
}
function getLoanOfferingAddresses(
Tx transaction
)
private
pure
returns (address[9])
{
return [
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.payer,
transaction.loanOffering.owner,
transaction.loanOffering.taker,
transaction.loanOffering.positionOwner,
transaction.loanOffering.feeRecipient,
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.takerFeeToken
];
}
function getLoanOfferingValues256(
Tx transaction
)
private
pure
returns (uint256[7])
{
return [
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minAmount,
transaction.loanOffering.rates.minHeldToken,
transaction.loanOffering.rates.lenderFee,
transaction.loanOffering.rates.takerFee,
transaction.loanOffering.expirationTimestamp,
transaction.loanOffering.salt
];
}
function getLoanOfferingValues32(
Tx transaction
)
private
pure
returns (uint32[4])
{
return [
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.rates.interestPeriod
];
}
}
// File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol
/**
* @title IncreaseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreaseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned loan. Margin will call this on the owner of a loan during increasePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan size was successfully increased.
*
* @param payer Lender adding additional funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Principal amount to be added to the position
* @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or
* zero if increaseWithoutCounterparty() is used).
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol
/**
* @title IncreasePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreasePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned position. Margin will call this on the owner of a position during increasePosition()
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the position size was successfully increased.
*
* @param trader Address initiating the addition of funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Amount of principal to be added to the position
* @return This address to accept, a different address to ask that contract
*/
function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/IncreasePositionImpl.sol
/**
* @title IncreasePositionImpl
* @author dYdX
*
* This library contains the implementation for the increasePosition function of Margin
*/
library IncreasePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function increasePositionImpl(
MarginState.State storage state,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (uint256)
{
// Also ensures that the position exists
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
BorrowShared.Tx memory transaction = parseIncreasePositionTx(
position,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature
);
validateIncrease(state, transaction, position);
doBorrowAndSell(state, transaction, orderData);
updateState(
position,
transaction.positionId,
transaction.principal,
transaction.lenderAmount,
transaction.loanOffering.payer
);
// LOG EVENT
recordPositionIncreased(transaction, position);
return transaction.lenderAmount;
}
function increaseWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 principalToAdd
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Disallow adding 0 principal
require(
principalToAdd > 0,
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal"
);
// Disallow additions after maximum duration
require(
block.timestamp < uint256(position.startTimestamp).add(position.maxDuration),
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration"
);
uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal(
state,
position,
positionId,
principalToAdd
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
heldTokenAmount
);
updateState(
position,
positionId,
principalToAdd,
0, // lent amount
msg.sender
);
emit PositionIncreased(
positionId,
msg.sender,
msg.sender,
position.owner,
position.lender,
"",
address(0),
0,
principalToAdd,
0,
heldTokenAmount,
true
);
return heldTokenAmount;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
// Calculate the number of heldTokens to add
uint256 collateralToAdd = getCollateralNeededForAddedPrincipal(
state,
state.positions[transaction.positionId],
transaction.positionId,
transaction.principal
);
// Do pre-exchange validations
BorrowShared.validateTxPreSell(state, transaction);
// Calculate and deposit owedToken
uint256 maxHeldTokenFromSell = MathHelpers.maxUint256();
if (!transaction.depositInHeldToken) {
transaction.depositAmount =
getOwedTokenDeposit(transaction, collateralToAdd, orderData);
BorrowShared.doDepositOwedToken(state, transaction);
maxHeldTokenFromSell = collateralToAdd;
}
// Sell owedToken for heldToken using the exchange wrapper
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
maxHeldTokenFromSell
);
// Calculate and deposit heldToken
if (transaction.depositInHeldToken) {
require(
transaction.heldTokenFromSell <= collateralToAdd,
"IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken"
);
transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell);
BorrowShared.doDepositHeldToken(state, transaction);
}
// Make sure the actual added collateral is what is expected
assert(transaction.collateralAmount == collateralToAdd);
// Do post-exchange validations
BorrowShared.doPostSell(state, transaction);
}
function getOwedTokenDeposit(
BorrowShared.Tx transaction,
uint256 collateralToAdd,
bytes orderData
)
private
view
returns (uint256)
{
uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost(
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
collateralToAdd,
orderData
);
require(
transaction.lenderAmount <= totalOwedToken,
"IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required"
);
return totalOwedToken.sub(transaction.lenderAmount);
}
function validateIncrease(
MarginState.State storage state,
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
view
{
assert(MarginCommon.containsPositionImpl(state, transaction.positionId));
require(
position.callTimeLimit <= transaction.loanOffering.callTimeLimit,
"IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position"
);
// require the position to end no later than the loanOffering's maximum acceptable end time
uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration);
uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration);
require(
positionEndTimestamp <= offeringEndTimestamp,
"IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position"
);
require(
block.timestamp < positionEndTimestamp,
"IncreasePositionImpl#validateIncrease: Position has passed its maximum duration"
);
}
function getCollateralNeededForAddedPrincipal(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalToAdd
)
private
view
returns (uint256)
{
uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
return MathHelpers.getPartialAmountRoundedUp(
principalToAdd,
position.principal,
heldTokenBalance
);
}
function updateState(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalAdded,
uint256 owedTokenLent,
address loanPayer
)
private
{
position.principal = position.principal.add(principalAdded);
address owner = position.owner;
address lender = position.lender;
// Ensure owner consent
increasePositionOnBehalfOfRecurse(
owner,
msg.sender,
positionId,
principalAdded
);
// Ensure lender consent
increaseLoanOnBehalfOfRecurse(
lender,
loanPayer,
positionId,
principalAdded,
owedTokenLent
);
}
function increasePositionOnBehalfOfRecurse(
address contractAddr,
address trader,
bytes32 positionId,
uint256 principalAdded
)
private
{
// Assume owner approval if not a smart contract and they increased their own position
if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf(
trader,
positionId,
principalAdded
);
if (newContractAddr != contractAddr) {
increasePositionOnBehalfOfRecurse(
newContractAddr,
trader,
positionId,
principalAdded
);
}
}
function increaseLoanOnBehalfOfRecurse(
address contractAddr,
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 amountLent
)
private
{
// Assume lender approval if not a smart contract and they increased their own loan
if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf(
payer,
positionId,
principalAdded,
amountLent
);
if (newContractAddr != contractAddr) {
increaseLoanOnBehalfOfRecurse(
newContractAddr,
payer,
positionId,
principalAdded,
amountLent
);
}
}
function recordPositionIncreased(
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
{
emit PositionIncreased(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
position.owner,
position.lender,
transaction.loanOffering.loanHash,
transaction.loanOffering.feeRecipient,
transaction.lenderAmount,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseIncreasePositionTx(
MarginCommon.Position storage position,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
uint256 principal = values256[7];
uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principal,
block.timestamp
);
assert(lenderAmount >= principal);
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: positionId,
owner: position.owner,
principal: principal,
lenderAmount: lenderAmount,
loanOffering: parseLoanOfferingFromIncreasePositionTx(
position,
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[6],
depositInHeldToken: depositInHeldToken,
depositAmount: 0, // set later
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOfferingFromIncreasePositionTx(
MarginCommon.Position storage position,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: position.owedToken,
heldToken: position.heldToken,
payer: addresses[0],
owner: position.lender,
taker: addresses[1],
positionOwner: addresses[2],
feeRecipient: addresses[3],
lenderFeeToken: addresses[4],
takerFeeToken: addresses[5],
rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferingRatesFromIncreasePositionTx(
MarginCommon.Position storage position,
uint256[8] values256
)
private
view
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: position.interestRate,
interestPeriod: position.interestPeriod
});
return rates;
}
}
// File: contracts/margin/impl/MarginStorage.sol
/**
* @title MarginStorage
* @author dYdX
*
* This contract serves as the storage for the entire state of MarginStorage
*/
contract MarginStorage {
MarginState.State state;
}
// File: contracts/margin/impl/LoanGetters.sol
/**
* @title LoanGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any loan
* offering stored in the dYdX protocol.
*/
contract LoanGetters is MarginStorage {
// ============ Public Constant Functions ============
/**
* Gets the principal amount of a loan offering that is no longer available.
*
* @param loanHash Unique hash of the loan offering
* @return The total unavailable amount of the loan offering, which is equal to the
* filled amount plus the canceled amount.
*/
function getLoanUnavailableAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash);
}
/**
* Gets the total amount of owed token lent for a loan.
*
* @param loanHash Unique hash of the loan offering
* @return The total filled amount of the loan offering.
*/
function getLoanFilledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanFills[loanHash];
}
/**
* Gets the amount of a loan offering that has been canceled.
*
* @param loanHash Unique hash of the loan offering
* @return The total canceled amount of the loan offering.
*/
function getLoanCanceledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanCancels[loanHash];
}
}
// File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol
/**
* @title CancelMarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses cancel a
* margin-call for a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CancelMarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the margin-call was successfully canceled.
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/lender/MarginCallDelegator.sol
/**
* @title MarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses margin-call a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface MarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan was successfully margin-called.
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/LoanImpl.sol
/**
* @title LoanImpl
* @author dYdX
*
* This library contains the implementation for the following functions of Margin:
*
* - marginCall
* - cancelMarginCallImpl
* - cancelLoanOffering
*/
library LoanImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
// ============ Public Implementation Functions ============
function marginCallImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requiredDeposit
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp == 0,
"LoanImpl#marginCallImpl: The position has already been margin-called"
);
// Ensure lender consent
marginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
requiredDeposit
);
position.callTimestamp = TimestampHelper.getBlockTimestamp32();
position.requiredDeposit = requiredDeposit;
emit MarginCallInitiated(
positionId,
position.lender,
position.owner,
requiredDeposit
);
}
function cancelMarginCallImpl(
MarginState.State storage state,
bytes32 positionId
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp > 0,
"LoanImpl#cancelMarginCallImpl: Position has not been margin-called"
);
// Ensure lender consent
cancelMarginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId
);
state.positions[positionId].callTimestamp = 0;
state.positions[positionId].requiredDeposit = 0;
emit MarginCallCanceled(
positionId,
position.lender,
position.owner,
0
);
}
function cancelLoanOfferingImpl(
MarginState.State storage state,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
public
returns (uint256)
{
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32
);
require(
msg.sender == loanOffering.payer,
"LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel"
);
require(
loanOffering.expirationTimestamp > block.timestamp,
"LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired"
);
uint256 remainingAmount = loanOffering.rates.maxAmount.sub(
MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash)
);
uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount);
// If the loan was already fully canceled, then just return 0 amount was canceled
if (amountToCancel == 0) {
return 0;
}
state.loanCancels[loanOffering.loanHash] =
state.loanCancels[loanOffering.loanHash].add(amountToCancel);
emit LoanOfferingCanceled(
loanOffering.loanHash,
loanOffering.payer,
loanOffering.feeRecipient,
amountToCancel
);
return amountToCancel;
}
// ============ Private Helper-Functions ============
function marginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId,
uint256 requiredDeposit
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
MarginCallDelegator(contractAddr).marginCallOnBehalfOf(
msg.sender,
positionId,
requiredDeposit
);
if (newContractAddr != contractAddr) {
marginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId,
requiredDeposit
);
}
}
function cancelMarginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf(
msg.sender,
positionId
);
if (newContractAddr != contractAddr) {
cancelMarginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId
);
}
}
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[0],
heldToken: addresses[1],
payer: addresses[2],
owner: addresses[3],
taker: addresses[4],
positionOwner: addresses[5],
feeRecipient: addresses[6],
lenderFeeToken: addresses[7],
takerFeeToken: addresses[8],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: new bytes(0)
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[7] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
interestRate: values32[2],
lenderFee: values256[3],
takerFee: values256[4],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/MarginAdmin.sol
/**
* @title MarginAdmin
* @author dYdX
*
* Contains admin functions for the Margin contract
* The owner can put Margin into various close-only modes, which will disallow new position creation
*/
contract MarginAdmin is Ownable {
// ============ Enums ============
// All functionality enabled
uint8 private constant OPERATION_STATE_OPERATIONAL = 0;
// Only closing functions + cancelLoanOffering allowed (marginCall, closePosition,
// cancelLoanOffering, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1;
// Only closing functions allowed (marginCall, closePosition, closePositionDirectly,
// forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2;
// Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3;
// This operation state (and any higher) is invalid
uint8 private constant OPERATION_STATE_INVALID = 4;
// ============ Events ============
/**
* Event indicating the operation state has changed
*/
event OperationStateChanged(
uint8 from,
uint8 to
);
// ============ State Variables ============
uint8 public operationState;
// ============ Constructor ============
constructor()
public
Ownable()
{
operationState = OPERATION_STATE_OPERATIONAL;
}
// ============ Modifiers ============
modifier onlyWhileOperational() {
require(
operationState == OPERATION_STATE_OPERATIONAL,
"MarginAdmin#onlyWhileOperational: Can only call while operational"
);
_;
}
modifier cancelLoanOfferingStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY,
"MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state"
);
_;
}
modifier closePositionStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY
|| operationState == OPERATION_STATE_CLOSE_ONLY,
"MarginAdmin#closePositionStateControl: Invalid operation state"
);
_;
}
modifier closePositionDirectlyStateControl() {
_;
}
// ============ Owner-Only State-Changing Functions ============
function setOperationState(
uint8 newState
)
external
onlyOwner
{
require(
newState < OPERATION_STATE_INVALID,
"MarginAdmin#setOperationState: newState is not a valid operation state"
);
if (newState != operationState) {
emit OperationStateChanged(
operationState,
newState
);
operationState = newState;
}
}
}
// File: contracts/margin/impl/MarginEvents.sol
/**
* @title MarginEvents
* @author dYdX
*
* Contains events for the Margin contract.
*
* NOTE: Any Margin function libraries that use events will need to both define the event here
* and copy the event into the library itself as libraries don't support sharing events
*/
contract MarginEvents {
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a position was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
}
// File: contracts/margin/impl/OpenPositionImpl.sol
/**
* @title OpenPositionImpl
* @author dYdX
*
* This library contains the implementation for the openPosition function of Margin
*/
library OpenPositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openPositionImpl(
MarginState.State storage state,
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (bytes32)
{
BorrowShared.Tx memory transaction = parseOpenTx(
addresses,
values256,
values32,
depositInHeldToken,
signature
);
require(
!MarginCommon.positionHasExisted(state, transaction.positionId),
"OpenPositionImpl#openPositionImpl: positionId already exists"
);
doBorrowAndSell(state, transaction, orderData);
// Before doStoreNewPosition() so that PositionOpened event is before Transferred events
recordPositionOpened(
transaction
);
doStoreNewPosition(
state,
transaction
);
return transaction.positionId;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
BorrowShared.validateTxPreSell(state, transaction);
if (transaction.depositInHeldToken) {
BorrowShared.doDepositHeldToken(state, transaction);
} else {
BorrowShared.doDepositOwedToken(state, transaction);
}
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
MathHelpers.maxUint256()
);
BorrowShared.doPostSell(state, transaction);
}
function doStoreNewPosition(
MarginState.State storage state,
BorrowShared.Tx memory transaction
)
private
{
MarginCommon.storeNewPosition(
state,
transaction.positionId,
MarginCommon.Position({
owedToken: transaction.loanOffering.owedToken,
heldToken: transaction.loanOffering.heldToken,
lender: transaction.loanOffering.owner,
owner: transaction.owner,
principal: transaction.principal,
requiredDeposit: 0,
callTimeLimit: transaction.loanOffering.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: transaction.loanOffering.maxDuration,
interestRate: transaction.loanOffering.rates.interestRate,
interestPeriod: transaction.loanOffering.rates.interestPeriod
}),
transaction.loanOffering.payer
);
}
function recordPositionOpened(
BorrowShared.Tx transaction
)
private
{
emit PositionOpened(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
transaction.loanOffering.loanHash,
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.feeRecipient,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseOpenTx(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[9]),
owner: addresses[0],
principal: values256[7],
lenderAmount: values256[7],
loanOffering: parseLoanOffering(
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[10],
depositInHeldToken: depositInHeldToken,
depositAmount: values256[8],
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOffering(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[1],
heldToken: addresses[2],
payer: addresses[3],
owner: addresses[4],
taker: addresses[5],
positionOwner: addresses[6],
feeRecipient: addresses[7],
lenderFeeToken: addresses[8],
takerFeeToken: addresses[9],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[10] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: values32[2],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol
/**
* @title OpenWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the openWithoutCounterparty
* function of Margin
*/
library OpenWithoutCounterpartyImpl {
// ============ Structs ============
struct Tx {
bytes32 positionId;
address positionOwner;
address owedToken;
address heldToken;
address loanOwner;
uint256 principal;
uint256 deposit;
uint32 callTimeLimit;
uint32 maxDuration;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openWithoutCounterpartyImpl(
MarginState.State storage state,
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
public
returns (bytes32)
{
Tx memory openTx = parseTx(
addresses,
values256,
values32
);
validate(
state,
openTx
);
Vault(state.VAULT).transferToVault(
openTx.positionId,
openTx.heldToken,
msg.sender,
openTx.deposit
);
recordPositionOpened(
openTx
);
doStoreNewPosition(
state,
openTx
);
return openTx.positionId;
}
// ============ Private Helper-Functions ============
function doStoreNewPosition(
MarginState.State storage state,
Tx memory openTx
)
private
{
MarginCommon.storeNewPosition(
state,
openTx.positionId,
MarginCommon.Position({
owedToken: openTx.owedToken,
heldToken: openTx.heldToken,
lender: openTx.loanOwner,
owner: openTx.positionOwner,
principal: openTx.principal,
requiredDeposit: 0,
callTimeLimit: openTx.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: openTx.maxDuration,
interestRate: openTx.interestRate,
interestPeriod: openTx.interestPeriod
}),
msg.sender
);
}
function validate(
MarginState.State storage state,
Tx memory openTx
)
private
view
{
require(
!MarginCommon.positionHasExisted(state, openTx.positionId),
"openWithoutCounterpartyImpl#validate: positionId already exists"
);
require(
openTx.principal > 0,
"openWithoutCounterpartyImpl#validate: principal cannot be 0"
);
require(
openTx.owedToken != address(0),
"openWithoutCounterpartyImpl#validate: owedToken cannot be 0"
);
require(
openTx.owedToken != openTx.heldToken,
"openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken"
);
require(
openTx.positionOwner != address(0),
"openWithoutCounterpartyImpl#validate: positionOwner cannot be 0"
);
require(
openTx.loanOwner != address(0),
"openWithoutCounterpartyImpl#validate: loanOwner cannot be 0"
);
require(
openTx.maxDuration > 0,
"openWithoutCounterpartyImpl#validate: maxDuration cannot be 0"
);
require(
openTx.interestPeriod <= openTx.maxDuration,
"openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration"
);
}
function recordPositionOpened(
Tx memory openTx
)
private
{
emit PositionOpened(
openTx.positionId,
msg.sender,
msg.sender,
bytes32(0),
openTx.owedToken,
openTx.heldToken,
address(0),
openTx.principal,
0,
openTx.deposit,
openTx.interestRate,
openTx.callTimeLimit,
openTx.maxDuration,
true
);
}
// ============ Parsing Functions ============
function parseTx(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
private
view
returns (Tx memory)
{
Tx memory openTx = Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[2]),
positionOwner: addresses[0],
owedToken: addresses[1],
heldToken: addresses[2],
loanOwner: addresses[3],
principal: values256[0],
deposit: values256[1],
callTimeLimit: values32[0],
maxDuration: values32[1],
interestRate: values32[2],
interestPeriod: values32[3]
});
return openTx;
}
}
// File: contracts/margin/impl/PositionGetters.sol
/**
* @title PositionGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any position
* stored in the dYdX protocol.
*/
contract PositionGetters is MarginStorage {
using SafeMath for uint256;
// ============ Public Constant Functions ============
/**
* Gets if a position is currently open.
*
* @param positionId Unique ID of the position
* @return True if the position is exists and is open
*/
function containsPosition(
bytes32 positionId
)
external
view
returns (bool)
{
return MarginCommon.containsPositionImpl(state, positionId);
}
/**
* Gets if a position is currently margin-called.
*
* @param positionId Unique ID of the position
* @return True if the position is margin-called
*/
function isPositionCalled(
bytes32 positionId
)
external
view
returns (bool)
{
return (state.positions[positionId].callTimestamp > 0);
}
/**
* Gets if a position was previously open and is now closed.
*
* @param positionId Unique ID of the position
* @return True if the position is now closed
*/
function isPositionClosed(
bytes32 positionId
)
external
view
returns (bool)
{
return state.closedPositions[positionId];
}
/**
* Gets the total amount of owedToken ever repaid to the lender for a position.
*
* @param positionId Unique ID of the position
* @return Total amount of owedToken ever repaid
*/
function getTotalOwedTokenRepaidToLender(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.totalOwedTokenRepaidToLender[positionId];
}
/**
* Gets the amount of heldToken currently locked up in Vault for a particular position.
*
* @param positionId Unique ID of the position
* @return The amount of heldToken
*/
function getPositionBalance(
bytes32 positionId
)
external
view
returns (uint256)
{
return MarginCommon.getPositionBalanceImpl(state, positionId);
}
/**
* Gets the time until the interest fee charged for the position will increase.
* Returns 1 if the interest fee increases every second.
* Returns 0 if the interest fee will never increase again.
*
* @param positionId Unique ID of the position
* @return The number of seconds until the interest fee will increase
*/
function getTimeUntilInterestIncrease(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed(
position,
block.timestamp
);
uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp);
if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration
return 0;
} else {
// nextStep is the final second at which the calculated interest fee is the same as it
// is currently, so add 1 to get the correct value
return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed);
}
}
/**
* Gets the amount of owedTokens currently needed to close the position completely, including
* interest fees.
*
* @param positionId Unique ID of the position
* @return The number of owedTokens
*/
function getPositionOwedAmount(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
return MarginCommon.calculateOwedAmount(
position,
position.principal,
block.timestamp
);
}
/**
* Gets the amount of owedTokens needed to close a given principal amount of the position at a
* given time, including interest fees.
*
* @param positionId Unique ID of the position
* @param principalToClose Amount of principal being closed
* @param timestamp Block timestamp in seconds of close
* @return The number of owedTokens owed
*/
function getPositionOwedAmountAtTime(
bytes32 positionId,
uint256 principalToClose,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getPositionOwedAmountAtTime: Requested time before position started"
);
return MarginCommon.calculateOwedAmount(
position,
principalToClose,
timestamp
);
}
/**
* Gets the amount of owedTokens that can be borrowed from a lender to add a given principal
* amount to the position at a given time.
*
* @param positionId Unique ID of the position
* @param principalToAdd Amount being added to principal
* @param timestamp Block timestamp in seconds of addition
* @return The number of owedTokens that will be borrowed
*/
function getLenderAmountForIncreasePositionAtTime(
bytes32 positionId,
uint256 principalToAdd,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start"
);
return MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principalToAdd,
timestamp
);
}
// ============ All Properties ============
/**
* Get a Position by id. This does not validate the position exists. If the position does not
* exist, all 0's will be returned.
*
* @param positionId Unique ID of the position
* @return Addresses corresponding to:
*
* [0] = owedToken
* [1] = heldToken
* [2] = lender
* [3] = owner
*
* Values corresponding to:
*
* [0] = principal
* [1] = requiredDeposit
*
* Values corresponding to:
*
* [0] = callTimeLimit
* [1] = startTimestamp
* [2] = callTimestamp
* [3] = maxDuration
* [4] = interestRate
* [5] = interestPeriod
*/
function getPosition(
bytes32 positionId
)
external
view
returns (
address[4],
uint256[2],
uint32[6]
)
{
MarginCommon.Position storage position = state.positions[positionId];
return (
[
position.owedToken,
position.heldToken,
position.lender,
position.owner
],
[
position.principal,
position.requiredDeposit
],
[
position.callTimeLimit,
position.startTimestamp,
position.callTimestamp,
position.maxDuration,
position.interestRate,
position.interestPeriod
]
);
}
// ============ Individual Properties ============
function getPositionLender(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].lender;
}
function getPositionOwner(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owner;
}
function getPositionHeldToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].heldToken;
}
function getPositionOwedToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owedToken;
}
function getPositionPrincipal(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].principal;
}
function getPositionInterestRate(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].interestRate;
}
function getPositionRequiredDeposit(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].requiredDeposit;
}
function getPositionStartTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].startTimestamp;
}
function getPositionCallTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimestamp;
}
function getPositionCallTimeLimit(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimeLimit;
}
function getPositionMaxDuration(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].maxDuration;
}
function getPositioninterestPeriod(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].interestPeriod;
}
}
// File: contracts/margin/impl/TransferImpl.sol
/**
* @title TransferImpl
* @author dYdX
*
* This library contains the implementation for the transferPosition and transferLoan functions of
* Margin
*/
library TransferImpl {
// ============ Public Implementation Functions ============
function transferLoanImpl(
MarginState.State storage state,
bytes32 positionId,
address newLender
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferLoanImpl: Position does not exist"
);
address originalLender = state.positions[positionId].lender;
require(
msg.sender == originalLender,
"TransferImpl#transferLoanImpl: Only lender can transfer ownership"
);
require(
newLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of loan.
// That is, newLender may pass ownership to a different address.
address finalLender = TransferInternal.grantLoanOwnership(
positionId,
originalLender,
newLender);
require(
finalLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].lender = finalLender;
}
function transferPositionImpl(
MarginState.State storage state,
bytes32 positionId,
address newOwner
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferPositionImpl: Position does not exist"
);
address originalOwner = state.positions[positionId].owner;
require(
msg.sender == originalOwner,
"TransferImpl#transferPositionImpl: Only position owner can transfer ownership"
);
require(
newOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of position.
// That is, newOwner may pass ownership to a different address.
address finalOwner = TransferInternal.grantPositionOwnership(
positionId,
originalOwner,
newOwner);
require(
finalOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].owner = finalOwner;
}
}
// File: contracts/margin/Margin.sol
/**
* @title Margin
* @author dYdX
*
* This contract is used to facilitate margin trading as per the dYdX protocol
*/
contract Margin is
ReentrancyGuard,
MarginStorage,
MarginEvents,
MarginAdmin,
LoanGetters,
PositionGetters
{
using SafeMath for uint256;
// ============ Constructor ============
constructor(
address vault,
address proxy
)
public
MarginAdmin()
{
state = MarginState.State({
VAULT: vault,
TOKEN_PROXY: proxy
});
}
// ============ Public State Changing Functions ============
/**
* Open a margin position. Called by the margin trader who must provide both a
* signed loan offering as well as a DEX Order with which to sell the owedToken.
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan payer
* [4] = loan owner
* [5] = loan taker
* [6] = loan position owner
* [7] = loan fee recipient
* [8] = loan lender fee token
* [9] = loan taker fee token
* [10] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = position amount of principal
* [8] = deposit amount
* [9] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Unique ID for the new position
*/
function openPosition(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenPositionImpl.openPositionImpl(
state,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Open a margin position without a counterparty. The caller will serve as both the
* lender and the position owner
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan owner
*
* @param values256 Values corresponding to:
*
* [0] = principal
* [1] = deposit amount
* [2] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = call time limit (in seconds)
* [1] = maxDuration (in seconds)
* [2] = interest rate (annual nominal percentage times 10**6)
* [3] = interest update period (in seconds)
*
* @return Unique ID for the new position
*/
function openWithoutCounterparty(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl(
state,
addresses,
values256,
values32
);
}
/**
* Increase the size of a position. Funds will be borrowed from the loan payer and sold as per
* the position. The amount of owedToken borrowed from the lender will be >= the amount of
* principal added, as it will incorporate interest already earned by the position so far.
*
* @param positionId Unique ID of the position
* @param addresses Addresses corresponding to:
*
* [0] = loan payer
* [1] = loan taker
* [2] = loan position owner
* [3] = loan fee recipient
* [4] = loan lender fee token
* [5] = loan taker fee token
* [6] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender
* will be >= this amount)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be pulled in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Amount of owedTokens pulled from the lender
*/
function increasePosition(
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increasePositionImpl(
state,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Increase a position directly by putting up heldToken. The caller will serve as both the
* lender and the position owner
*
* @param positionId Unique ID of the position
* @param principalToAdd Principal amount to add to the position
* @return Amount of heldToken pulled from the msg.sender
*/
function increaseWithoutCounterparty(
bytes32 positionId,
uint256 principalToAdd
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increaseWithoutCounterpartyImpl(
state,
positionId,
principalToAdd
);
}
/**
* Close a position. May be called by the owner or with the approval of the owner. May provide
* an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient
* is sent the resulting payout.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param exchangeWrapper Address of the exchange wrapper
* @param payoutInHeldToken True to pay out the payoutRecipient in heldToken,
* False to pay out the payoutRecipient in owedToken
* @param order Order object to be passed to the exchange wrapper
* @return Values corresponding to:
* 1) Principal of position closed
* 2) Amount of tokens (heldToken if payoutInHeldtoken is true,
* owedToken otherwise) received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePosition(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes order
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
order
);
}
/**
* Helper to close a position by paying owedToken directly rather than using an exchangeWrapper.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePositionDirectly(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionDirectlyStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
new bytes(0)
);
}
/**
* Reduce the size of a position and withdraw a proportional amount of heldToken from the vault.
* Must be approved by both the position owner and lender.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* 3) The amount allowed by the lender if closer != lender
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the msg.sender
*/
function closeWithoutCounterparty(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256)
{
return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient
);
}
/**
* Margin-call a position. Only callable with the approval of the position lender. After the
* call, the position owner will have time equal to the callTimeLimit of the position to close
* the position. If the owner does not close the position, the lender can recover the collateral
* in the position.
*
* @param positionId Unique ID of the position
* @param requiredDeposit Amount of deposit the position owner will have to put up to cancel
* the margin-call. Passing in 0 means the margin call cannot be
* canceled by depositing
*/
function marginCall(
bytes32 positionId,
uint256 requiredDeposit
)
external
nonReentrant
{
LoanImpl.marginCallImpl(
state,
positionId,
requiredDeposit
);
}
/**
* Cancel a margin-call. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
*/
function cancelMarginCall(
bytes32 positionId
)
external
onlyWhileOperational
nonReentrant
{
LoanImpl.cancelMarginCallImpl(state, positionId);
}
/**
* Used to recover the heldTokens held as collateral. Is callable after the maximum duration of
* the loan has expired or the loan has been margin-called for the duration of the callTimeLimit
* but remains unclosed. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return Amount of heldToken recovered
*/
function forceRecoverCollateral(
bytes32 positionId,
address recipient
)
external
nonReentrant
returns (uint256)
{
return ForceRecoverCollateralImpl.forceRecoverCollateralImpl(
state,
positionId,
recipient
);
}
/**
* Deposit additional heldToken as collateral for a position. Cancels margin-call if:
* 0 < position.requiredDeposit < depositAmount. Only callable by the position owner.
*
* @param positionId Unique ID of the position
* @param depositAmount Additional amount in heldToken to deposit
*/
function depositCollateral(
bytes32 positionId,
uint256 depositAmount
)
external
onlyWhileOperational
nonReentrant
{
DepositCollateralImpl.depositCollateralImpl(
state,
positionId,
depositAmount
);
}
/**
* Cancel an amount of a loan offering. Only callable by the loan offering's payer.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan position owner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param cancelAmount Amount to cancel
* @return Amount that was canceled
*/
function cancelLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
external
cancelLoanOfferingStateControl
nonReentrant
returns (uint256)
{
return LoanImpl.cancelLoanOfferingImpl(
state,
addresses,
values256,
values32,
cancelAmount
);
}
/**
* Transfer ownership of a loan to a new address. This new address will be entitled to all
* payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it
* must implement the LoanOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the loan
*/
function transferLoan(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferLoanImpl(
state,
positionId,
who);
}
/**
* Transfer ownership of a position to a new address. This new address will be entitled to all
* payouts. Only callable by the owner of a position. If "who" is a contract, it must implement
* the PositionOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the position
*/
function transferPosition(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferPositionImpl(
state,
positionId,
who);
}
// ============ Public Constant Functions ============
/**
* Gets the address of the Vault contract that holds and accounts for tokens.
*
* @return The address of the Vault contract
*/
function getVaultAddress()
external
view
returns (address)
{
return state.VAULT;
}
/**
* Gets the address of the TokenProxy contract that accounts must set allowance on in order to
* make loans or open/close positions.
*
* @return The address of the TokenProxy contract
*/
function getTokenProxyAddress()
external
view
returns (address)
{
return state.TOKEN_PROXY;
}
}
// File: contracts/margin/interfaces/OnlyMargin.sol
/**
* @title OnlyMargin
* @author dYdX
*
* Contract to store the address of the main Margin contract and trust only that address to call
* certain functions.
*/
contract OnlyMargin {
// ============ Constants ============
// Address of the known and trusted Margin contract on the blockchain
address public DYDX_MARGIN;
// ============ Constructor ============
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
// ============ Modifiers ============
modifier onlyMargin()
{
require(
msg.sender == DYDX_MARGIN,
"OnlyMargin#onlyMargin: Only Margin can call"
);
_;
}
}
// File: contracts/margin/external/lib/LoanOfferingParser.sol
/**
* @title LoanOfferingParser
* @author dYdX
*
* Contract for LoanOfferingVerifiers to parse arguments
*/
contract LoanOfferingParser {
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes signature
)
internal
pure
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering;
fillLoanOfferingAddresses(loanOffering, addresses);
fillLoanOfferingValues256(loanOffering, values256);
fillLoanOfferingValues32(loanOffering, values32);
loanOffering.signature = signature;
return loanOffering;
}
function fillLoanOfferingAddresses(
MarginCommon.LoanOffering memory loanOffering,
address[9] addresses
)
private
pure
{
loanOffering.owedToken = addresses[0];
loanOffering.heldToken = addresses[1];
loanOffering.payer = addresses[2];
loanOffering.owner = addresses[3];
loanOffering.taker = addresses[4];
loanOffering.positionOwner = addresses[5];
loanOffering.feeRecipient = addresses[6];
loanOffering.lenderFeeToken = addresses[7];
loanOffering.takerFeeToken = addresses[8];
}
function fillLoanOfferingValues256(
MarginCommon.LoanOffering memory loanOffering,
uint256[7] values256
)
private
pure
{
loanOffering.rates.maxAmount = values256[0];
loanOffering.rates.minAmount = values256[1];
loanOffering.rates.minHeldToken = values256[2];
loanOffering.rates.lenderFee = values256[3];
loanOffering.rates.takerFee = values256[4];
loanOffering.expirationTimestamp = values256[5];
loanOffering.salt = values256[6];
}
function fillLoanOfferingValues32(
MarginCommon.LoanOffering memory loanOffering,
uint32[4] values32
)
private
pure
{
loanOffering.callTimeLimit = values32[0];
loanOffering.maxDuration = values32[1];
loanOffering.rates.interestRate = values32[2];
loanOffering.rates.interestPeriod = values32[3];
}
}
// File: contracts/margin/external/lib/MarginHelper.sol
/**
* @title MarginHelper
* @author dYdX
*
* This library contains helper functions for interacting with Margin
*/
library MarginHelper {
function getPosition(
address DYDX_MARGIN,
bytes32 positionId
)
internal
view
returns (MarginCommon.Position memory)
{
(
address[4] memory addresses,
uint256[2] memory values256,
uint32[6] memory values32
) = Margin(DYDX_MARGIN).getPosition(positionId);
return MarginCommon.Position({
owedToken: addresses[0],
heldToken: addresses[1],
lender: addresses[2],
owner: addresses[3],
principal: values256[0],
requiredDeposit: values256[1],
callTimeLimit: values32[0],
startTimestamp: values32[1],
callTimestamp: values32[2],
maxDuration: values32[3],
interestRate: values32[4],
interestPeriod: values32[5]
});
}
}
// File: contracts/margin/external/BucketLender/BucketLender.sol
/**
* @title BucketLender
* @author dYdX
*
* On-chain shared lender that allows anyone to deposit tokens into this contract to be used to
* lend tokens for a particular margin position.
*
* - Each bucket has three variables:
* - Available Amount
* - The available amount of tokens that the bucket has to lend out
* - Outstanding Principal
* - The amount of principal that the bucket is responsible for in the margin position
* - Weight
* - Used to keep track of each account's weighted ownership within a bucket
* - Relative weight between buckets is meaningless
* - Only accounts' relative weight within a bucket matters
*
* - Token Deposits:
* - Go into a particular bucket, determined by time since the start of the position
* - If the position has not started: bucket = 0
* - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME)
* - This is always the highest bucket; no higher bucket yet exists
* - Increase the bucket's Available Amount
* - Increase the bucket's weight and the account's weight in that bucket
*
* - Token Withdrawals:
* - Can be from any bucket with available amount
* - Decrease the bucket's Available Amount
* - Decrease the bucket's weight and the account's weight in that bucket
*
* - Increasing the Position (Lending):
* - The lowest buckets with Available Amount are used first
* - Decreases Available Amount
* - Increases Outstanding Principal
*
* - Decreasing the Position (Being Paid-Back)
* - The highest buckets with Outstanding Principal are paid back first
* - Decreases Outstanding Principal
* - Increases Available Amount
*
*
* - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from
* those buckets for a longer period of time.
* - Deposits in the same bucket earn the same interest rate.
* - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not
* making the maximum interest).
* - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket
with Available Amount
*/
contract BucketLender is
Ownable,
OnlyMargin,
LoanOwner,
IncreaseLoanDelegator,
MarginCallDelegator,
CancelMarginCallDelegator,
ForceRecoverCollateralDelegator,
LoanOfferingParser,
LoanOfferingVerifier,
ReentrancyGuard
{
using SafeMath for uint256;
using TokenInteract for address;
// ============ Events ============
event Deposit(
address indexed beneficiary,
uint256 bucket,
uint256 amount,
uint256 weight
);
event Withdraw(
address indexed withdrawer,
uint256 bucket,
uint256 weight,
uint256 owedTokenWithdrawn,
uint256 heldTokenWithdrawn
);
event PrincipalIncreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event PrincipalDecreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event AvailableIncreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
event AvailableDecreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
// ============ State Variables ============
/**
* Available Amount is the amount of tokens that is available to be lent by each bucket.
* These tokens are also available to be withdrawn by the accounts that have weight in the
* bucket.
*/
// Available Amount for each bucket
mapping(uint256 => uint256) public availableForBucket;
// Total Available Amount
uint256 public availableTotal;
/**
* Outstanding Principal is the share of the margin position's principal that each bucket
* is responsible for. That is, each bucket with Outstanding Principal is owed
* (Outstanding Principal)*E^(RT) owedTokens in repayment.
*/
// Outstanding Principal for each bucket
mapping(uint256 => uint256) public principalForBucket;
// Total Outstanding Principal
uint256 public principalTotal;
/**
* Weight determines an account's proportional share of a bucket. Relative weights have no
* meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has
* no meaning. However, the relative weight of two accounts within the same bucket is equal to
* the accounts' shares in the bucket and are therefore proportional to the payout that they
* should expect from withdrawing from that bucket.
*/
// Weight for each account in each bucket
mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount;
// Total Weight for each bucket
mapping(uint256 => uint256) public weightForBucket;
/**
* The critical bucket is:
* - Greater-than-or-equal-to The highest bucket with Outstanding Principal
* - Less-than-or-equal-to the lowest bucket with Available Amount
*
* It is equal to both of these values in most cases except in an edge cases where the two
* buckets are different. This value is cached to find such a bucket faster than looping through
* all possible buckets.
*/
uint256 public criticalBucket = 0;
/**
* Latest cached value for totalOwedTokenRepaidToLender.
* This number updates on the dYdX Margin base protocol whenever the position is
* partially-closed, but this contract is not notified at that time. Therefore, it is updated
* upon increasing the position or when depositing/withdrawing
*/
uint256 public cachedRepaidAmount = 0;
// True if the position was closed from force-recovering the collateral
bool public wasForceClosed = false;
// ============ Constants ============
// Unique ID of the position
bytes32 public POSITION_ID;
// Address of the token held in the position as collateral
address public HELD_TOKEN;
// Address of the token being lent
address public OWED_TOKEN;
// Time between new buckets
uint32 public BUCKET_TIME;
// Interest rate of the position
uint32 public INTEREST_RATE;
// Interest period of the position
uint32 public INTEREST_PERIOD;
// Maximum duration of the position
uint32 public MAX_DURATION;
// Margin-call time-limit of the position
uint32 public CALL_TIMELIMIT;
// (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position
uint32 public MIN_HELD_TOKEN_NUMERATOR;
uint32 public MIN_HELD_TOKEN_DENOMINATOR;
// Accounts that are permitted to margin-call positions (or cancel the margin call)
mapping(address => bool) public TRUSTED_MARGIN_CALLERS;
// Accounts that are permitted to withdraw on behalf of any address
mapping(address => bool) public TRUSTED_WITHDRAWERS;
// ============ Constructor ============
constructor(
address margin,
bytes32 positionId,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] trustedMarginCallers,
address[] trustedWithdrawers
)
public
OnlyMargin(margin)
{
POSITION_ID = positionId;
HELD_TOKEN = heldToken;
OWED_TOKEN = owedToken;
require(
parameters[0] != 0,
"BucketLender#constructor: BUCKET_TIME cannot be zero"
);
BUCKET_TIME = parameters[0];
INTEREST_RATE = parameters[1];
INTEREST_PERIOD = parameters[2];
MAX_DURATION = parameters[3];
CALL_TIMELIMIT = parameters[4];
MIN_HELD_TOKEN_NUMERATOR = parameters[5];
MIN_HELD_TOKEN_DENOMINATOR = parameters[6];
// Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS
uint256 i = 0;
for (i = 0; i < trustedMarginCallers.length; i++) {
TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true;
}
for (i = 0; i < trustedWithdrawers.length; i++) {
TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true;
}
// Set maximum allowance on proxy
OWED_TOKEN.approve(
Margin(margin).getTokenProxyAddress(),
MathHelpers.maxUint256()
);
}
// ============ Modifiers ============
modifier onlyPosition(bytes32 positionId) {
require(
POSITION_ID == positionId,
"BucketLender#onlyPosition: Incorrect position"
);
_;
}
// ============ Margin-Only State-Changing Functions ============
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* @param addresses Loan offering addresses
* @param values256 Loan offering uint256s
* @param values32 Loan offering uint32s
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
Margin(DYDX_MARGIN).containsPosition(POSITION_ID),
"BucketLender#verifyLoanOffering: This contract should not open a new position"
);
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32,
signature
);
// CHECK ADDRESSES
assert(loanOffering.owedToken == OWED_TOKEN);
assert(loanOffering.heldToken == HELD_TOKEN);
assert(loanOffering.payer == address(this));
assert(loanOffering.owner == address(this));
require(
loanOffering.taker == address(0),
"BucketLender#verifyLoanOffering: loanOffering.taker is non-zero"
);
require(
loanOffering.feeRecipient == address(0),
"BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero"
);
require(
loanOffering.positionOwner == address(0),
"BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero"
);
require(
loanOffering.lenderFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero"
);
require(
loanOffering.takerFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero"
);
// CHECK VALUES256
require(
loanOffering.rates.maxAmount == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect"
);
require(
loanOffering.rates.minAmount == 0,
"BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero"
);
require(
loanOffering.rates.minHeldToken == 0,
"BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero"
);
require(
loanOffering.rates.lenderFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero"
);
require(
loanOffering.rates.takerFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero"
);
require(
loanOffering.expirationTimestamp == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: expirationTimestamp is incorrect"
);
require(
loanOffering.salt == 0,
"BucketLender#verifyLoanOffering: loanOffering.salt is non-zero"
);
// CHECK VALUES32
require(
loanOffering.callTimeLimit == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect"
);
require(
loanOffering.maxDuration == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect"
);
assert(loanOffering.rates.interestRate == INTEREST_RATE);
assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD);
// no need to require anything about loanOffering.signature
return address(this);
}
/**
* Called by the Margin contract when anyone transfers ownership of a loan to this contract.
* This function initializes this contract and returns this address to indicate to Margin
* that it is willing to take ownership of the loan.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address on success, throw otherwise
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
uint256 initialPrincipal = position.principal;
uint256 minHeldToken = MathHelpers.getPartialAmount(
uint256(MIN_HELD_TOKEN_NUMERATOR),
uint256(MIN_HELD_TOKEN_DENOMINATOR),
initialPrincipal
);
assert(initialPrincipal > 0);
assert(principalTotal == 0);
assert(from != address(this)); // position must be opened without lending from this position
require(
position.owedToken == OWED_TOKEN,
"BucketLender#receiveLoanOwnership: Position owedToken mismatch"
);
require(
position.heldToken == HELD_TOKEN,
"BucketLender#receiveLoanOwnership: Position heldToken mismatch"
);
require(
position.maxDuration == MAX_DURATION,
"BucketLender#receiveLoanOwnership: Position maxDuration mismatch"
);
require(
position.callTimeLimit == CALL_TIMELIMIT,
"BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch"
);
require(
position.interestRate == INTEREST_RATE,
"BucketLender#receiveLoanOwnership: Position interestRate mismatch"
);
require(
position.interestPeriod == INTEREST_PERIOD,
"BucketLender#receiveLoanOwnership: Position interestPeriod mismatch"
);
require(
Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken,
"BucketLender#receiveLoanOwnership: Not enough heldToken as collateral"
);
// set relevant constants
principalForBucket[0] = initialPrincipal;
principalTotal = initialPrincipal;
weightForBucket[0] = weightForBucket[0].add(initialPrincipal);
weightForBucketForAccount[0][from] =
weightForBucketForAccount[0][from].add(initialPrincipal);
return address(this);
}
/**
* Called by Margin when additional value is added onto the position this contract
* is lending for. Balance is added to the address that loaned the additional tokens.
*
* @param payer Address that loaned the additional tokens
* @param positionId Unique ID of the position
* @param principalAdded Amount that was added to the position
* @param lentAmount Amount of owedToken lent
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
Margin margin = Margin(DYDX_MARGIN);
require(
payer == address(this),
"BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position"
);
require(
!margin.isPositionCalled(POSITION_ID),
"BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called"
);
// This function is only called after the state has been updated in the base protocol;
// thus, the principal in the base protocol will equal the principal after the increase
uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID);
uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded);
// principalTotal was the principal after the previous increase
accountForClose(principalTotal.sub(principalBeforeIncrease));
accountForIncrease(principalAdded, lentAmount);
assert(principalTotal == principalAfterIncrease);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[caller],
"BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted"
);
require(
depositAmount == 0, // prevents depositing from canceling the margin-call
"BucketLender#marginCallOnBehalfOf: Deposit amount must be zero"
);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[canceler],
"BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted"
);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address /* recoverer */,
bytes32 positionId,
address recipient
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
return forceRecoverCollateralInternal(recipient);
}
// ============ Public State-Changing Functions ============
/**
* Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if
* part of the position has been closed since the last position increase.
*/
function rebalanceBuckets()
external
nonReentrant
{
rebalanceBucketsInternal();
}
/**
* Allows users to deposit owedToken into this contract. Allowance must be set on this contract
* for "token" in at least the amount "amount".
*
* @param beneficiary The account that will be entitled to this depoit
* @param amount The amount of owedToken to deposit
* @return The bucket number that was deposited into
*/
function deposit(
address beneficiary,
uint256 amount
)
external
nonReentrant
returns (uint256)
{
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
require(
beneficiary != address(0),
"BucketLender#deposit: Beneficiary cannot be the zero address"
);
require(
amount != 0,
"BucketLender#deposit: Cannot deposit zero tokens"
);
require(
!margin.isPositionClosed(positionId),
"BucketLender#deposit: Cannot deposit after the position is closed"
);
require(
!margin.isPositionCalled(positionId),
"BucketLender#deposit: Cannot deposit while the position is margin-called"
);
rebalanceBucketsInternal();
OWED_TOKEN.transferFrom(
msg.sender,
address(this),
amount
);
uint256 bucket = getCurrentBucket();
uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket));
uint256 weightToAdd = 0;
if (effectiveAmount == 0) {
weightToAdd = amount; // first deposit in bucket
} else {
weightToAdd = MathHelpers.getPartialAmount(
amount,
effectiveAmount,
weightForBucket[bucket]
);
}
require(
weightToAdd != 0,
"BucketLender#deposit: Cannot deposit for zero weight"
);
// update state
updateAvailable(bucket, amount, true);
weightForBucketForAccount[bucket][beneficiary] =
weightForBucketForAccount[bucket][beneficiary].add(weightToAdd);
weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd);
emit Deposit(
beneficiary,
bucket,
amount,
weightToAdd
);
return bucket;
}
/**
* Allows users to withdraw their lent funds. An account can withdraw its weighted share of the
* bucket.
*
* While the position is open, a bucket's share is equal to:
* Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest)
* Held Token: 0
*
* After the position is closed, a bucket's share is equal to:
* Owed Token: (Available Amount)
* Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal)
*
* @param buckets The bucket numbers to withdraw from
* @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens
* withdrawn will be at least this amount, but not necessarily more.
* Withdrawing the same weight from different buckets does not necessarily
* return the same amounts from those buckets. In order to withdraw as many
* tokens as possible, use the maximum uint256.
* @param onBehalfOf The address to withdraw on behalf of
* @return 1) The number of owedTokens withdrawn
* 2) The number of heldTokens withdrawn
*/
function withdraw(
uint256[] buckets,
uint256[] maxWeights,
address onBehalfOf
)
external
nonReentrant
returns (uint256, uint256)
{
require(
buckets.length == maxWeights.length,
"BucketLender#withdraw: The lengths of the input arrays must match"
);
if (onBehalfOf != msg.sender) {
require(
TRUSTED_WITHDRAWERS[msg.sender],
"BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others"
);
}
rebalanceBucketsInternal();
// decide if some bucket is unable to be withdrawn from (is locked)
// the zero value represents no-lock
uint256 lockedBucket = 0;
if (
Margin(DYDX_MARGIN).containsPosition(POSITION_ID) &&
criticalBucket == getCurrentBucket()
) {
lockedBucket = criticalBucket;
}
uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken
uint256 maxHeldToken = 0;
if (wasForceClosed) {
maxHeldToken = HELD_TOKEN.balanceOf(address(this));
}
for (uint256 i = 0; i < buckets.length; i++) {
uint256 bucket = buckets[i];
// prevent withdrawing from the current bucket if it is also the critical bucket
if ((bucket != 0) && (bucket == lockedBucket)) {
continue;
}
(uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket(
onBehalfOf,
bucket,
maxWeights[i],
maxHeldToken
);
results[0] = results[0].add(owedTokenForBucket);
results[1] = results[1].add(heldTokenForBucket);
}
// Transfer share of owedToken
OWED_TOKEN.transfer(msg.sender, results[0]);
HELD_TOKEN.transfer(msg.sender, results[1]);
return (results[0], results[1]);
}
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to this contract by calling
* deposit() will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
rebalanceBucketsInternal();
uint256 amount = token.balanceOf(address(this));
if (token == OWED_TOKEN) {
amount = amount.sub(availableTotal);
} else if (token == HELD_TOKEN) {
require(
!wasForceClosed,
"BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed"
);
}
token.transfer(to, amount);
return amount;
}
// ============ Public Getter Functions ============
/**
* Get the current bucket number that funds will be deposited into. This is also the highest
* bucket so far.
*
* @return The highest bucket and the one that funds will be deposited into
*/
function getCurrentBucket()
public
view
returns (uint256)
{
// load variables from storage;
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
uint32 bucketTime = BUCKET_TIME;
assert(!margin.isPositionClosed(positionId));
// if position not created, allow deposits in the first bucket
if (!margin.containsPosition(positionId)) {
return 0;
}
// return the number of BUCKET_TIME periods elapsed since the position start, rounded-up
uint256 startTimestamp = margin.getPositionStartTimestamp(positionId);
return block.timestamp.sub(startTimestamp).div(bucketTime).add(1);
}
/**
* Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of
* the bucket multiplied by the interest accrued in the position. If the position is closed,
* then any outstanding principal will never be repaid in the form of owedToken.
*
* @param bucket The bucket number
* @return The amount of owedToken that this bucket expects to be paid-back if the posi
*/
function getBucketOwedAmount(
uint256 bucket
)
public
view
returns (uint256)
{
// if the position is completely closed, then the outstanding principal will never be repaid
if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) {
return 0;
}
uint256 lentPrincipal = principalForBucket[bucket];
// the bucket has no outstanding principal
if (lentPrincipal == 0) {
return 0;
}
// get the total amount of owedToken that would be paid back at this time
uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime(
POSITION_ID,
principalTotal,
uint32(block.timestamp)
);
// return the bucket's share
return MathHelpers.getPartialAmount(
lentPrincipal,
principalTotal,
owedAmount
);
}
// ============ Internal Functions ============
function forceRecoverCollateralInternal(
address recipient
)
internal
returns (address)
{
require(
recipient == address(this),
"BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract"
);
rebalanceBucketsInternal();
wasForceClosed = true;
return address(this);
}
// ============ Private Helper Functions ============
/**
* Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the
* state if part of the position has been closed since the last position increase.
*/
function rebalanceBucketsInternal()
private
{
// if force-closed, don't update the outstanding principal values; they are needed to repay
// lenders with heldToken
if (wasForceClosed) {
return;
}
uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID);
accountForClose(principalTotal.sub(marginPrincipal));
assert(principalTotal == marginPrincipal);
}
/**
* Updates the state variables at any time. Only does anything after the position has been
* closed or partially-closed since the last time this function was called.
*
* - Increases the available amount in the highest buckets with outstanding principal
* - Decreases the principal amount in those buckets
*
* @param principalRemoved Amount of principal closed since the last update
*/
function accountForClose(
uint256 principalRemoved
)
private
{
if (principalRemoved == 0) {
return;
}
uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID);
assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved);
uint256 principalToSub = principalRemoved;
uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount);
uint256 criticalBucketTemp = criticalBucket;
// loop over buckets in reverse order starting with the critical bucket
for (
uint256 bucket = criticalBucketTemp;
principalToSub > 0;
bucket--
) {
assert(bucket <= criticalBucketTemp); // no underflow on bucket
uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]);
if (principalTemp == 0) {
continue;
}
uint256 availableTemp = MathHelpers.getPartialAmount(
principalTemp,
principalToSub,
availableToAdd
);
updateAvailable(bucket, availableTemp, true);
updatePrincipal(bucket, principalTemp, false);
principalToSub = principalToSub.sub(principalTemp);
availableToAdd = availableToAdd.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToSub == 0);
assert(availableToAdd == 0);
setCriticalBucket(criticalBucketTemp);
cachedRepaidAmount = newRepaidAmount;
}
/**
* Updates the state variables when a position is increased.
*
* - Decreases the available amount in the lowest buckets with available token
* - Increases the principal amount in those buckets
*
* @param principalAdded Amount of principal added to the position
* @param lentAmount Amount of owedToken lent
*/
function accountForIncrease(
uint256 principalAdded,
uint256 lentAmount
)
private
{
require(
lentAmount <= availableTotal,
"BucketLender#accountForIncrease: No lending not-accounted-for funds"
);
uint256 principalToAdd = principalAdded;
uint256 availableToSub = lentAmount;
uint256 criticalBucketTemp;
// loop over buckets in order starting from the critical bucket
uint256 lastBucket = getCurrentBucket();
for (
uint256 bucket = criticalBucket;
principalToAdd > 0;
bucket++
) {
assert(bucket <= lastBucket); // should never go past the last bucket
uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]);
if (availableTemp == 0) {
continue;
}
uint256 principalTemp = MathHelpers.getPartialAmount(
availableTemp,
availableToSub,
principalToAdd
);
updateAvailable(bucket, availableTemp, false);
updatePrincipal(bucket, principalTemp, true);
principalToAdd = principalToAdd.sub(principalTemp);
availableToSub = availableToSub.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToAdd == 0);
assert(availableToSub == 0);
setCriticalBucket(criticalBucketTemp);
}
/**
* Withdraw
*
* @param onBehalfOf The account for which to withdraw for
* @param bucket The bucket number to withdraw from
* @param maxWeight The maximum weight to withdraw
* @param maxHeldToken The total amount of heldToken that has been force-recovered
* @return 1) The number of owedTokens withdrawn
* 2) The number of heldTokens withdrawn
*/
function withdrawSingleBucket(
address onBehalfOf,
uint256 bucket,
uint256 maxWeight,
uint256 maxHeldToken
)
private
returns (uint256, uint256)
{
// calculate the user's share
uint256 bucketWeight = weightForBucket[bucket];
if (bucketWeight == 0) {
return (0, 0);
}
uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf];
uint256 weightToWithdraw = Math.min256(maxWeight, userWeight);
if (weightToWithdraw == 0) {
return (0, 0);
}
// update state
weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw);
weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw);
// calculate for owedToken
uint256 owedTokenToWithdraw = withdrawOwedToken(
bucket,
weightToWithdraw,
bucketWeight
);
// calculate for heldToken
uint256 heldTokenToWithdraw = withdrawHeldToken(
bucket,
weightToWithdraw,
bucketWeight,
maxHeldToken
);
emit Withdraw(
onBehalfOf,
bucket,
weightToWithdraw,
owedTokenToWithdraw,
heldTokenToWithdraw
);
return (owedTokenToWithdraw, heldTokenToWithdraw);
}
/**
* Helper function to withdraw earned owedToken from this contract.
*
* @param bucket The bucket number to withdraw from
* @param userWeight The amount of weight the user is using to withdraw
* @param bucketWeight The total weight of the bucket
* @return The amount of owedToken being withdrawn
*/
function withdrawOwedToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight
)
private
returns (uint256)
{
// amount to return for the bucket
uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
availableForBucket[bucket].add(getBucketOwedAmount(bucket))
);
// check that there is enough token to give back
require(
owedTokenToWithdraw <= availableForBucket[bucket],
"BucketLender#withdrawOwedToken: There must be enough available owedToken"
);
// update amounts
updateAvailable(bucket, owedTokenToWithdraw, false);
return owedTokenToWithdraw;
}
/**
* Helper function to withdraw heldToken from this contract.
*
* @param bucket The bucket number to withdraw from
* @param userWeight The amount of weight the user is using to withdraw
* @param bucketWeight The total weight of the bucket
* @param maxHeldToken The total amount of heldToken available to withdraw
* @return The amount of heldToken being withdrawn
*/
function withdrawHeldToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight,
uint256 maxHeldToken
)
private
returns (uint256)
{
if (maxHeldToken == 0) {
return 0;
}
// user's principal for the bucket
uint256 principalForBucketForAccount = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
principalForBucket[bucket]
);
uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount(
principalForBucketForAccount,
principalTotal,
maxHeldToken
);
updatePrincipal(bucket, principalForBucketForAccount, false);
return heldTokenToWithdraw;
}
// ============ Setter Functions ============
/**
* Changes the critical bucket variable
*
* @param bucket The value to set criticalBucket to
*/
function setCriticalBucket(
uint256 bucket
)
private
{
// don't spend the gas to sstore unless we need to change the value
if (criticalBucket == bucket) {
return;
}
criticalBucket = bucket;
}
/**
* Changes the available owedToken amount. This changes both the variable to track the total
* amount as well as the variable to track a particular bucket.
*
* @param bucket The bucket number
* @param amount The amount to change the available amount by
* @param increase True if positive change, false if negative change
*/
function updateAvailable(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = availableTotal.add(amount);
newForBucket = availableForBucket[bucket].add(amount);
emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
} else {
newTotal = availableTotal.sub(amount);
newForBucket = availableForBucket[bucket].sub(amount);
emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
}
availableTotal = newTotal;
availableForBucket[bucket] = newForBucket;
}
/**
* Changes the principal amount. This changes both the variable to track the total
* amount as well as the variable to track a particular bucket.
*
* @param bucket The bucket number
* @param amount The amount to change the principal amount by
* @param increase True if positive change, false if negative change
*/
function updatePrincipal(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = principalTotal.add(amount);
newForBucket = principalForBucket[bucket].add(amount);
emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
} else {
newTotal = principalTotal.sub(amount);
newForBucket = principalForBucket[bucket].sub(amount);
emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
}
principalTotal = newTotal;
principalForBucket[bucket] = newForBucket;
}
}
// File: contracts/margin/external/BucketLender/BucketLenderFactory.sol
/**
* @title BucketLenderFactory
* @author dYdX
*
* Contract that allows anyone to deploy a BucketLender contract by sending a transaction.
*/
contract BucketLenderFactory {
// ============ Events ============
event BucketLenderCreated(
address indexed creator,
address indexed owner,
bytes32 indexed positionId,
address at
);
// ============ State Variables ============
// Address of the Margin contract for the dYdX Margin Trading Protocol
address public DYDX_MARGIN;
// ============ Constructor ============
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
// ============ Public Functions ============
/**
* Deploy a new BucketLender contract to the blockchain
*
* @param positionId Unique ID of the position
* @param owner Address to which ownership of the BucketLender will be transferred
* @param heldToken Address of the token held in the position as collateral
* @param owedToken Address of the token being lent by the BucketLender
* @param parameters Values corresponding to:
*
* [0] = number of seconds per bucket
* [1] = interest rate
* [2] = interest period
* [3] = maximum loan duration
* [4] = margin-call timelimit
* [5] = numerator of minimum heldToken-per-owedToken
* [6] = denominator of minimum heldToken-per-owedToken
*
* @param marginCallers Accounts that are permitted to margin-call positions (or cancel the margin call)
* @return The address of the new BucketLender contract
*/
function createBucketLender(
bytes32 positionId,
address owner,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] marginCallers,
address[] withdrawers
)
external
returns (address)
{
address newBucketLender = new BucketLender(
DYDX_MARGIN,
positionId,
heldToken,
owedToken,
parameters,
marginCallers,
withdrawers
);
BucketLender(newBucketLender).transferOwnership(owner);
emit BucketLenderCreated(
msg.sender,
owner,
positionId,
newBucketLender
);
return newBucketLender;
}
} | Transfer ownership of a loan to a new address. This new address will be entitled to all payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it must implement the LoanOwner interface. positionId Unique ID of the position who New owner of the loan/ | function transferLoan(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferLoanImpl(
state,
positionId,
who);
}
| 1,594,153 |
pragma solidity 0.5.1;
import "./erc721.sol";
import "./erc721-token-receiver.sol";
import "../math/safe-math.sol";
import "../utils/supports-interface.sol";
import "../utils/address-utils.sol";
/**
* @dev Implementation of ERC-721 non-fungible token standard.
*/
contract NFToken is
ERC721,
SupportsInterface
{
using SafeMath for uint256;
using AddressUtils for address;
/**
* @dev Magic value of a smart contract that can recieve NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
/**
* @dev A mapping from NFT ID to the address that owns it.
*/
mapping (uint256 => address) internal idToOwner;
/**
* @dev Mapping from NFT ID to approved address.
*/
mapping (uint256 => address) internal idToApproval;
/**
* @dev Mapping from owner address to count of his tokens.
*/
mapping (address => uint256) private ownerToNFTokenCount;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
* @param _from Sender of NFT (if address is zero address it indicates token creation).
* @param _to Receiver of NFT (if address is zero address it indicates token destruction).
* @param _tokenId The NFT that got transfered.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
* @param _owner Owner of NFT.
* @param _approved Address that we are approving.
* @param _tokenId NFT which we are approving.
*/
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
* @param _owner Owner of NFT.
* @param _operator Address to which we are setting operator rights.
* @param _approved Status of operator rights(true if operator rights are given and false if
* revoked).
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev Guarantees that the msg.sender is an owner or operator of the given NFT.
* @param _tokenId ID of the NFT to validate.
*/
modifier canOperate(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender]);
_;
}
/**
* @dev Guarantees that the msg.sender is allowed to transfer NFT.
* @param _tokenId ID of the NFT to transfer.
*/
modifier canTransfer(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender
|| idToApproval[_tokenId] == msg.sender
|| ownerToOperators[tokenOwner][msg.sender]
);
_;
}
/**
* @dev Guarantees that _tokenId is a valid Token.
* @param _tokenId ID of the NFT to validate.
*/
modifier validNFToken(
uint256 _tokenId
)
{
require(idToOwner[_tokenId] != address(0));
_;
}
/**
* @dev Contract constructor.
*/
constructor()
public
{
supportedInterfaces[0x80ac58cd] = true; // ERC721
}
/**
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
{
_safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they maybe be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
_transfer(_to, _tokenId);
}
/**
* @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved Address to be approved for the given NFT ID.
* @param _tokenId ID of the token to be approved.
*/
function approve(
address _approved,
uint256 _tokenId
)
external
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice This works even if sender doesn't own any tokens at the time.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external
{
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256)
{
require(_owner != address(0));
return _getOwnerNFTCount(_owner);
}
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0));
}
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId ID of the NFT to query the approval of.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
view
validNFToken(_tokenId)
returns (address)
{
return idToApproval[_tokenId];
}
/**
* @dev Checks if `_operator` is an approved operator for `_owner`.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool)
{
return ownerToOperators[_owner][_operator];
}
/**
* @dev Actually preforms the transfer.
* @notice Does NO checks.
* @param _to Address of a new owner.
* @param _tokenId The NFT that is being transferred.
*/
function _transfer(
address _to,
uint256 _tokenId
)
internal
{
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
/**
* @dev Mints a new NFT.
* @notice This is a private function which should be called from user-implemented external
* mint function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
*/
function _mint(
address _to,
uint256 _tokenId
)
internal
{
require(_to != address(0));
require(idToOwner[_tokenId] == address(0));
_addNFToken(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Burns a NFT.
* @notice This is a private function which should be called from user-implemented external
* burn function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
uint256 _tokenId
)
internal
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(tokenOwner, _tokenId);
emit Transfer(tokenOwner, address(0), _tokenId);
}
/**
* @dev Removes a NFT from owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function _removeNFToken(
address _from,
uint256 _tokenId
)
internal
{
require(idToOwner[_tokenId] == _from);
ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1;
delete idToOwner[_tokenId];
}
/**
* @dev Assignes a new NFT to owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to wich we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function _addNFToken(
address _to,
uint256 _tokenId
)
internal
{
require(idToOwner[_tokenId] == address(0));
idToOwner[_tokenId] = _to;
ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1);
}
/**
* @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable
* extension to remove double storage (gas optimization) of owner nft count.
* @param _owner Address for whom to query the count.
* @return Number of _owner NFTs.
*/
function _getOwnerNFTCount(
address _owner
)
internal
view
returns (uint256)
{
return ownerToNFTokenCount[_owner];
}
/**
* @dev Actually perform the safeTransferFrom.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
private
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
_transfer(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED);
}
}
/**
* @dev Clears the current approval of a given NFT ID.
* @param _tokenId ID of the NFT to be transferred.
*/
function _clearApproval(
uint256 _tokenId
)
private
{
if (idToApproval[_tokenId] != address(0))
{
delete idToApproval[_tokenId];
}
}
}
| Assignes a new NFT to owner. Use and override this function with caution. Wrong usage can have serious consequences. _to Address to wich we want to add the NFT. _tokenId Which NFT we want to add./ | function _addNFToken(
address _to,
uint256 _tokenId
)
internal
{
require(idToOwner[_tokenId] == address(0));
idToOwner[_tokenId] = _to;
ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1);
}
| 6,402,896 |
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../../TokenStakingEscrow.sol";
import "../../utils/OperatorParams.sol";
/// @notice TokenStaking contract library allowing to perform two-step stake
/// top-ups for existing delegations.
/// Top-up is a two-step process: it is initiated with a declared top-up value
/// and after waiting for at least the initialization period it can be
/// committed.
library TopUps {
using SafeMath for uint256;
using OperatorParams for uint256;
event TopUpInitiated(address indexed operator, uint256 topUp);
event TopUpCompleted(address indexed operator, uint256 newAmount);
struct TopUp {
uint256 amount;
uint256 createdAt;
}
struct Storage {
// operator -> TopUp
mapping(address => TopUp) topUps;
}
/// @notice Performs top-up in one step when stake is not yet initialized by
/// adding the top-up amount to the stake and resetting stake initialization
/// time counter.
/// @dev This function should be called only for not yet initialized stake.
/// @param value Top-up value, the number of tokens added to the stake.
/// @param operator Operator The operator with existing delegation to which
/// the tokens should be added to.
/// @param operatorParams Parameters of that operator, as stored in the
/// staking contract.
/// @param escrow Reference to TokenStakingEscrow contract.
/// @return New value of parameters. It should be updated for the operator
/// in the staking contract.
function instantComplete(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public returns (uint256 newParams) {
// Stake is not yet initialized so we don't need to check if the
// operator is not undelegating - initializing and undelegating at the
// same time is not possible. We do however, need to check whether the
// operator has not canceled its previous stake for that operator,
// depositing the stake it in the escrow. We do not want to allow
// resurrecting operators with cancelled stake by top-ups.
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
uint256 newAmount = operatorParams.getAmount().add(value);
newParams = operatorParams.setAmountAndCreationTimestamp(
newAmount,
block.timestamp
);
emit TopUpCompleted(operator, newAmount);
}
/// @notice Initiates top-up of the given value for tokens delegated to
/// the provided operator. If there is an existing top-up still
/// initializing, top-up values are summed up and initialization period
/// is set to the current block timestamp.
/// @dev This function should be called only for active operators with
/// initialized stake.
/// @param value Top-up value, the number of tokens added to the stake.
/// @param operator Operator The operator with existing delegation to which
/// the tokens should be added to.
/// @param operatorParams Parameters of that operator, as stored in the
/// staking contract.
/// @param escrow Reference to TokenStakingEscrow contract.
function initiate(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public {
// Stake is initialized, the operator is still active so we need
// to check if it's not undelegating.
require(!isUndelegating(operatorParams), "Stake undelegated");
// We also need to check if the stake for the operator is not already
// in the escrow because it's been previously cancelled.
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
TopUp memory awaiting = self.topUps[operator];
self.topUps[operator] = TopUp(awaiting.amount.add(value), now);
emit TopUpInitiated(operator, value);
}
/// @notice Commits the top-up if it passed the initialization period.
/// Tokens are added to the stake once the top-up is committed.
/// @param operator Operator The operator with a pending stake top-up.
/// @param initializationPeriod Stake initialization period.
function commit(
Storage storage self,
address operator,
uint256 operatorParams,
uint256 initializationPeriod
) public returns (uint256 newParams) {
TopUp memory topUp = self.topUps[operator];
require(topUp.amount > 0, "No top up to commit");
require(
now > topUp.createdAt.add(initializationPeriod),
"Stake is initializing"
);
uint256 newAmount = operatorParams.getAmount().add(topUp.amount);
newParams = operatorParams.setAmount(newAmount);
delete self.topUps[operator];
emit TopUpCompleted(operator, newAmount);
}
/// @notice Cancels pending, initiating top-up. If there is no initiating
/// top-up for the operator, function does nothing. This function should be
/// used when the stake is recovered to return tokens from a pending,
/// initiating top-up.
/// @param operator Operator The operator from which the stake is recovered.
function cancel(Storage storage self, address operator)
public
returns (uint256)
{
TopUp memory topUp = self.topUps[operator];
if (topUp.amount == 0) {
return 0;
}
delete self.topUps[operator];
return topUp.amount;
}
/// @notice Returns true if the given operatorParams indicate that the
/// operator is undelegating its stake or that it completed stake
/// undelegation.
/// @param operatorParams Parameters of the operator, as stored in the
/// staking contract.
function isUndelegating(uint256 operatorParams)
internal
view
returns (bool)
{
uint256 undelegatedAt = operatorParams.getUndelegationTimestamp();
return (undelegatedAt != 0) && (block.timestamp > undelegatedAt);
}
}
| Initiates top-up of the given value for tokens delegated to the provided operator. If there is an existing top-up still initializing, top-up values are summed up and initialization period is set to the current block timestamp. This function should be called only for active operators with initialized stake. value Top-up value, the number of tokens added to the stake. operator Operator The operator with existing delegation to which the tokens should be added to. operatorParams Parameters of that operator, as stored in the staking contract. escrow Reference to TokenStakingEscrow contract. Stake is initialized, the operator is still active so we need to check if it's not undelegating. We also need to check if the stake for the operator is not already in the escrow because it's been previously cancelled. | function initiate(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public {
require(!isUndelegating(operatorParams), "Stake undelegated");
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
TopUp memory awaiting = self.topUps[operator];
self.topUps[operator] = TopUp(awaiting.amount.add(value), now);
emit TopUpInitiated(operator, value);
}
| 1,057,346 |
./full_match/1/0x8F8381400BBAea7D9F9BAf388fd5Ae55deF64EDd/sources/contracts/PilatiNFT.sol | Used to get the max pilaties available limit. return uint256 for max pilaties available./ | function getMaxPilaties() public view returns (uint256) {
return MAX_PILATIS;
}
| 4,987,015 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../IStrategy.sol";
import "hardhat/console.sol";
//This strategy does not return all the funds to simulate slippage
contract MockLoosingStrategy is IStrategy {
mapping(address => uint256) depositedAmounts;
uint256 returnRate;
uint256 deployed;
constructor(uint256 _returnRate) {
returnRate = _returnRate;
}
function deploy(address _token) external override {
IERC20(_token).transfer(address(0), deployed - balance(_token));
uint256 internalBalance = IERC20(_token).balanceOf(address(this));
if (internalBalance > deployed) {
depositedAmounts[_token] += internalBalance - deployed;
}
deployed = internalBalance;
}
// Amount left in the contract may not be correct if reallocation occurs
function withdrawTo(
address _token,
uint256 _amount,
address _to
) external override returns (uint256) {
int256 roi = int256(balance(_token)) - int256(depositedAmounts[_token]);
if (int256(_amount) > roi) {
depositedAmounts[_token] = uint256(
int256(depositedAmounts[_token]) - (int256(_amount) - roi)
);
}
IERC20 token = IERC20(_token);
token.transfer(address(0), token.balanceOf(address(this)) - balance(_token));
token.transfer(_to, _amount);
deployed = token.balanceOf(address(this));
return _amount;
}
function emergencyWithdrawTo(address _token, address _to)
external
override
returns (uint256)
{
uint256 amount = deposited(_token);
IERC20(_token).transfer(_to, amount);
depositedAmounts[_token] = 0;
return amount;
}
function collectProfits(address _token, address _to)
external
override
returns (int256)
{
int256 profits = int256(balance(_token)) - int256(depositedAmounts[_token]);
IERC20(_token).transfer(_to, uint256(profits));
return profits;
}
function collectRewards(address _token, address _to)
external
override
returns (address[] memory)
{
// This farm compounds rewards into the base token
return new address[](0);
}
function deposited(address _token) public view override returns (uint256) {
return depositedAmounts[_token];
}
function balance(address _token) public view override returns (uint256) {
return (deployed * returnRate) / 100;
}
}
| Amount left in the contract may not be correct if reallocation occurs | function withdrawTo(
address _token,
uint256 _amount,
address _to
) external override returns (uint256) {
int256 roi = int256(balance(_token)) - int256(depositedAmounts[_token]);
if (int256(_amount) > roi) {
depositedAmounts[_token] = uint256(
int256(depositedAmounts[_token]) - (int256(_amount) - roi)
);
}
IERC20 token = IERC20(_token);
token.transfer(address(0), token.balanceOf(address(this)) - balance(_token));
token.transfer(_to, _amount);
deployed = token.balanceOf(address(this));
return _amount;
}
| 13,084,866 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
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/Strings.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./brightid/extensions/BrightIDValidatorOwnership.sol";
contract BrightIDSoulbound is Context, ERC165, BrightIDValidatorOwnership {
using Address for address;
using Strings for uint256;
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
// 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;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(
address verifier,
bytes32 context,
string memory name_,
string memory symbol_
) BrightIDValidatorOwnership(verifier, context) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Rescue the token `tokenId` without control of the owner address.
*/
function rescue(
bytes32[] calldata contextIds,
uint256 timestamp,
uint256 tokenId,
uint8 v,
bytes32 r,
bytes32 s
) public {
rescue(contextIds, timestamp, tokenId, v, r, s, "");
}
/**
* @dev See {BrightIDSoulbound-rescue}.
*/
function rescue(
bytes32[] calldata contextIds,
uint256 timestamp,
uint256 tokenId,
uint8 v,
bytes32 r,
bytes32 s,
bytes memory data
) public {
_validate(contextIds, timestamp, v, r, s);
address from;
address to;
(from, to) = _lookup(contextIds, tokenId);
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) 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 returns (uint256) {
require(owner != address(0), "BrightIDSoulbound: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "BrightIDSoulbound: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
require(_exists(tokenId), "BrightIDSoulbound: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Lookup an address tuple used for transferring token `tokenId`.
*
* Requirements:
*
* - length of `contextIds` must be greater than 1.
* - at least one element in `contextIds` resolves to the owner address of token `tokenId`.
*/
function _lookup(bytes32[] calldata contextIds, uint256 tokenId) internal view returns (address, address) {
address owner = ownerOf(tokenId);
for (uint256 i = 1; i < contextIds.length; i++) {
if (owner == _uuidToAddress[hashUUID(contextIds[i])]) {
return (_uuidToAddress[hashUUID(contextIds[i])], _uuidToAddress[hashUUID(contextIds[0])]);
}
}
revert("BrightIDSoulbound: no token to rescue");
}
/**
* @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 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),
"BrightIDSoulbound: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by accounts linked to the same BrightID.
*
* 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 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),
"BrightIDSoulbound: 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), "BrightIDSoulbound: mint to the zero address");
require(!_exists(tokenId), "BrightIDSoulbound: 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 = BrightIDSoulbound.ownerOf(tokenId);
_beforeTokenTransfer(owner, 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(to != address(0), "BrightIDSoulbound: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, 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("BrightIDSoulbound: 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 {}
}
| Rescue the token `tokenId` without control of the owner address./ | function rescue(
bytes32[] calldata contextIds,
uint256 timestamp,
uint256 tokenId,
uint8 v,
bytes32 r,
bytes32 s
) public {
rescue(contextIds, timestamp, tokenId, v, r, s, "");
}
| 7,222,729 |
// SPDX-License-Identifier: MIT
// File: contracts/Signer.sol
pragma solidity ^0.8.3;
/* Signature Verification
How to Sign and Verify
# Signing
1. Create message to sign
2. Hash the message
3. Sign the hash (off chain, keep your private key secret)
# Verify
1. Recreate hash from the original message
2. Recover signer from signature and hash
3. Compare recovered signer to claimed signer
*/
library VerifySignature {
/* 1. Unlock MetaMask account
ethereum.enable()
*/
/* 2. Get message hash to sign
getMessageHash(
0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C,
123,
"coffee and donuts",
1
)
hash = "0xcf36ac4f97dc10d91fc2cbb20d718e94a8cbfe0f82eaedc6a4aa38946fb797cd"
*/
function getMessageHash(
address _minter,
uint _quantity,
uint _nonce
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_minter, _quantity, _nonce));
}
/* 3. Sign message hash
# using browser
account = "copy paste account of signer here"
ethereum.request({ method: "personal_sign", params: [account, hash]}).then(console.log)
# using web3
web3.personal.sign(hash, web3.eth.defaultAccount, console.log)
Signature will be different for different accounts
0x993dab3dd91f5c6dc28e17439be475478f5635c92a56e17e82349d3fb2f166196f466c0b4e0c146f285204f0dcb13e5ae67bc33f4b888ec32dfe0a063e8f3f781b
*/
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)
);
}
/* 4. Verify signature
signer = 0xB273216C05A8c0D4F0a4Dd0d7Bae1D2EfFE636dd
to = 0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C
amount = 123
message = "coffee and donuts"
nonce = 1
signature =
0x993dab3dd91f5c6dc28e17439be475478f5635c92a56e17e82349d3fb2f166196f466c0b4e0c146f285204f0dcb13e5ae67bc33f4b888ec32dfe0a063e8f3f781b
*/
function verify(
address _signer,
address _minter,
uint _quantity,
uint _nonce,
bytes memory signature
) public pure returns (bool) {
bytes32 messageHash = getMessageHash(_minter, _quantity, _nonce);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == _signer;
}
function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature)
public
pure
returns (address)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory sig)
public
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)
}
}
// File: @openzeppelin/contracts/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 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;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: contracts/access/DeveloperAccess.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an developer) that can be granted exclusive access to
* specific functions.
*
* By default, the developer account will be the one that deploys the contract. This
* can later be changed with {transferDevelopership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyDeveloper`, which can be applied to your functions to restrict their use to
* the developer.
*/
abstract contract DeveloperAccess is Context {
address private _developer;
event DevelopershipTransferred(address indexed previousDeveloper, address indexed newDeveloper);
/**
* @dev Initializes the contract setting the deployer as the initial developer.
*/
constructor(address dev) {
_setDeveloper(dev);
}
/**
* @dev Returns the address of the current developer.
*/
function developer() public view virtual returns (address) {
return _developer;
}
/**
* @dev Throws if called by any account other than the developer.
*/
modifier onlyDeveloper() {
require(developer() == _msgSender(), "Ownable: caller is not the developer");
_;
}
/**
* @dev Leaves the contract without developer. It will not be possible to call
* `onlyDeveloper` functions anymore. Can only be called by the current developer.
*
* NOTE: Renouncing developership will leave the contract without an developer,
* thereby removing any functionality that is only available to the developer.
*/
function renounceDevelopership() public virtual onlyDeveloper {
_setDeveloper(address(0));
}
/**
* @dev Transfers developership of the contract to a new account (`newDeveloper`).
* Can only be called by the current developer.
*/
function transferDevelopership(address newDeveloper) public virtual onlyDeveloper {
require(newDeveloper != address(0), "Ownable: new developer is the zero address");
_setDeveloper(newDeveloper);
}
function _setDeveloper(address newDeveloper) private {
address oldDeveloper = _developer;
_developer = newDeveloper;
emit DevelopershipTransferred(oldDeveloper, newDeveloper);
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: prb-math/contracts/PRBMath.sol
pragma solidity >=0.8.4;
/// @notice Emitted when the result overflows uint256.
error PRBMath__MulDivFixedPointOverflow(uint256 prod1);
/// @notice Emitted when the result overflows uint256.
error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator);
/// @notice Emitted when one of the inputs is type(int256).min.
error PRBMath__MulDivSignedInputTooSmall();
/// @notice Emitted when the intermediary absolute result overflows int256.
error PRBMath__MulDivSignedOverflow(uint256 rAbs);
/// @notice Emitted when the input is MIN_SD59x18.
error PRBMathSD59x18__AbsInputTooSmall();
/// @notice Emitted when ceiling a number overflows SD59x18.
error PRBMathSD59x18__CeilOverflow(int256 x);
/// @notice Emitted when one of the inputs is MIN_SD59x18.
error PRBMathSD59x18__DivInputTooSmall();
/// @notice Emitted when one of the intermediary unsigned results overflows SD59x18.
error PRBMathSD59x18__DivOverflow(uint256 rAbs);
/// @notice Emitted when the input is greater than 133.084258667509499441.
error PRBMathSD59x18__ExpInputTooBig(int256 x);
/// @notice Emitted when the input is greater than 192.
error PRBMathSD59x18__Exp2InputTooBig(int256 x);
/// @notice Emitted when flooring a number underflows SD59x18.
error PRBMathSD59x18__FloorUnderflow(int256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMathSD59x18__FromIntOverflow(int256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMathSD59x18__FromIntUnderflow(int256 x);
/// @notice Emitted when the product of the inputs is negative.
error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y);
/// @notice Emitted when multiplying the inputs overflows SD59x18.
error PRBMathSD59x18__GmOverflow(int256 x, int256 y);
/// @notice Emitted when the input is less than or equal to zero.
error PRBMathSD59x18__LogInputTooSmall(int256 x);
/// @notice Emitted when one of the inputs is MIN_SD59x18.
error PRBMathSD59x18__MulInputTooSmall();
/// @notice Emitted when the intermediary absolute result overflows SD59x18.
error PRBMathSD59x18__MulOverflow(uint256 rAbs);
/// @notice Emitted when the intermediary absolute result overflows SD59x18.
error PRBMathSD59x18__PowuOverflow(uint256 rAbs);
/// @notice Emitted when the input is negative.
error PRBMathSD59x18__SqrtNegativeInput(int256 x);
/// @notice Emitted when the calculating the square root overflows SD59x18.
error PRBMathSD59x18__SqrtOverflow(int256 x);
/// @notice Emitted when addition overflows UD60x18.
error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y);
/// @notice Emitted when ceiling a number overflows UD60x18.
error PRBMathUD60x18__CeilOverflow(uint256 x);
/// @notice Emitted when the input is greater than 133.084258667509499441.
error PRBMathUD60x18__ExpInputTooBig(uint256 x);
/// @notice Emitted when the input is greater than 192.
error PRBMathUD60x18__Exp2InputTooBig(uint256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18.
error PRBMathUD60x18__FromUintOverflow(uint256 x);
/// @notice Emitted when multiplying the inputs overflows UD60x18.
error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y);
/// @notice Emitted when the input is less than 1.
error PRBMathUD60x18__LogInputTooSmall(uint256 x);
/// @notice Emitted when the calculating the square root overflows UD60x18.
error PRBMathUD60x18__SqrtOverflow(uint256 x);
/// @notice Emitted when subtraction underflows UD60x18.
error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y);
/// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library
/// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point
/// representation. When it does not, it is explicitly mentioned in the NatSpec documentation.
library PRBMath {
/// STRUCTS ///
struct SD59x18 {
int256 value;
}
struct UD60x18 {
uint256 value;
}
/// STORAGE ///
/// @dev How many trailing decimals can be represented.
uint256 internal constant SCALE = 1e18;
/// @dev Largest power of two divisor of SCALE.
uint256 internal constant SCALE_LPOTD = 262144;
/// @dev SCALE inverted mod 2^256.
uint256 internal constant SCALE_INVERSE =
78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// FUNCTIONS ///
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers.
/// See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp2(uint256 x) internal pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows
// because the initial result is 2^191 and all magic factors are less than 2^65.
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
// We're doing two things at the same time:
//
// 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for
// the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191
// rather than 192.
// 2. Convert the result to the unsigned 60.18-decimal fixed-point format.
//
// This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n".
result *= SCALE;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first one in the binary representation of x.
/// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return msb The index of the most significant bit as an uint256.
function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {
if (x >= 2**128) {
x >>= 128;
msb += 128;
}
if (x >= 2**64) {
x >>= 64;
msb += 64;
}
if (x >= 2**32) {
x >>= 32;
msb += 32;
}
if (x >= 2**16) {
x >>= 16;
msb += 16;
}
if (x >= 2**8) {
x >>= 8;
msb += 8;
}
if (x >= 2**4) {
x >>= 4;
msb += 4;
}
if (x >= 2**2) {
x >>= 2;
msb += 2;
}
if (x >= 2**1) {
// No need to shift x any more.
msb += 1;
}
}
/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Requirements:
/// - The denominator cannot be zero.
/// - The result must fit within uint256.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The multiplicand as an uint256.
/// @param y The multiplier as an uint256.
/// @param denominator The divisor as an uint256.
/// @return result The result as an uint256.
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
return result;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath__MulDivOverflow(prod1, denominator);
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
unchecked {
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 lpotdod = denominator & (~denominator + 1);
assembly {
// Divide denominator by lpotdod.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.
lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * lpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/// @notice Calculates floor(x*y÷1e18) with full precision.
///
/// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the
/// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of
/// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717.
///
/// Requirements:
/// - The result must fit within uint256.
///
/// Caveats:
/// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works.
/// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations:
/// 1. x * y = type(uint256).max * SCALE
/// 2. (x * y) % SCALE >= SCALE / 2
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 >= SCALE) {
revert PRBMath__MulDivFixedPointOverflow(prod1);
}
uint256 remainder;
uint256 roundUpUnit;
assembly {
remainder := mulmod(x, y, SCALE)
roundUpUnit := gt(remainder, 499999999999999999)
}
if (prod1 == 0) {
unchecked {
result = (prod0 / SCALE) + roundUpUnit;
return result;
}
}
assembly {
result := add(
mul(
or(
div(sub(prod0, remainder), SCALE_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1))
),
SCALE_INVERSE
),
roundUpUnit
)
}
}
/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately.
///
/// Requirements:
/// - None of the inputs can be type(int256).min.
/// - The result must fit within int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
function mulDivSigned(
int256 x,
int256 y,
int256 denominator
) internal pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath__MulDivSignedInputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 ax;
uint256 ay;
uint256 ad;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
ad = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of (x*y)÷denominator. The result must fit within int256.
uint256 rAbs = mulDiv(ax, ay, ad);
if (rAbs > uint256(type(int256).max)) {
revert PRBMath__MulDivSignedOverflow(rAbs);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs.
// If yes, the result should be negative.
result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as an uint256.
function sqrt(uint256 x) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// Set the initial guess to the closest power of two that is higher than x.
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 0x100000000000000000000000000000000) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 0x10000000000000000) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 0x100000000) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 0x10000) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 0x100) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 0x10) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 0x8) {
result <<= 1;
}
// The operations can never overflow because the result is max 2^127 when it enters this block.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1; // Seven iterations should be enough
uint256 roundedDownResult = x / result;
return result >= roundedDownResult ? roundedDownResult : result;
}
}
}
// File: prb-math/contracts/PRBMathUD60x18.sol
pragma solidity >=0.8.4;
/// @title PRBMathUD60x18
/// @author Paul Razvan Berg
/// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18
/// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60
/// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the
/// maximum values permitted by the Solidity type uint256.
library PRBMathUD60x18 {
/// @dev Half the SCALE number.
uint256 internal constant HALF_SCALE = 5e17;
/// @dev log2(e) as an unsigned 60.18-decimal fixed-point number.
uint256 internal constant LOG2_E = 1_442695040888963407;
/// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have.
uint256 internal constant MAX_UD60x18 =
115792089237316195423570985008687907853269984665640564039457_584007913129639935;
/// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have.
uint256 internal constant MAX_WHOLE_UD60x18 =
115792089237316195423570985008687907853269984665640564039457_000000000000000000;
/// @dev How many trailing decimals can be represented.
uint256 internal constant SCALE = 1e18;
/// @notice Calculates the arithmetic average of x and y, rounding down.
/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.
/// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number.
function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {
// The operations can never overflow.
unchecked {
// The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need
// to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.
result = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to MAX_WHOLE_UD60x18.
///
/// @param x The unsigned 60.18-decimal fixed-point number to ceil.
/// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number.
function ceil(uint256 x) internal pure returns (uint256 result) {
if (x > MAX_WHOLE_UD60x18) {
revert PRBMathUD60x18__CeilOverflow(x);
}
assembly {
// Equivalent to "x % SCALE" but faster.
let remainder := mod(x, SCALE)
// Equivalent to "SCALE - remainder" but faster.
let delta := sub(SCALE, remainder)
// Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster.
result := add(x, mul(delta, gt(remainder, 0)))
}
}
/// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number.
///
/// @dev Uses mulDiv to enable overflow-safe multiplication and division.
///
/// Requirements:
/// - The denominator cannot be zero.
///
/// @param x The numerator as an unsigned 60.18-decimal fixed-point number.
/// @param y The denominator as an unsigned 60.18-decimal fixed-point number.
/// @param result The quotient as an unsigned 60.18-decimal fixed-point number.
function div(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = PRBMath.mulDiv(x, SCALE, y);
}
/// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number.
/// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).
function e() internal pure returns (uint256 result) {
result = 2_718281828459045235;
}
/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the insight that e^x = 2^(x * log2(e)).
///
/// Requirements:
/// - All from "log2".
/// - x must be less than 133.084258667509499441.
///
/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp(uint256 x) internal pure returns (uint256 result) {
// Without this check, the value passed to "exp2" would be greater than 192.
if (x >= 133_084258667509499441) {
revert PRBMathUD60x18__ExpInputTooBig(x);
}
// Do the fixed-point multiplication inline to save gas.
unchecked {
uint256 doubleScaleProduct = x * LOG2_E;
result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within MAX_UD60x18.
///
/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp2(uint256 x) internal pure returns (uint256 result) {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) {
revert PRBMathUD60x18__Exp2InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x192x64 = (x << 64) / SCALE;
// Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.
result = PRBMath.exp2(x192x64);
}
}
/// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x.
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The unsigned 60.18-decimal fixed-point number to floor.
/// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number.
function floor(uint256 x) internal pure returns (uint256 result) {
assembly {
// Equivalent to "x % SCALE" but faster.
let remainder := mod(x, SCALE)
// Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster.
result := sub(x, mul(remainder, gt(remainder, 0)))
}
}
/// @notice Yields the excess beyond the floor of x.
/// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of.
/// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number.
function frac(uint256 x) internal pure returns (uint256 result) {
assembly {
result := mod(x, SCALE)
}
}
/// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation.
///
/// @dev Requirements:
/// - x must be less than or equal to MAX_UD60x18 divided by SCALE.
///
/// @param x The basic integer to convert.
/// @param result The same number in unsigned 60.18-decimal fixed-point representation.
function fromUint(uint256 x) internal pure returns (uint256 result) {
unchecked {
if (x > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__FromUintOverflow(x);
}
result = x * SCALE;
}
}
/// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.
///
/// @dev Requirements:
/// - x * y must fit within MAX_UD60x18, lest it overflows.
///
/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function gm(uint256 x, uint256 y) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xy = x * y;
if (xy / x != y) {
revert PRBMathUD60x18__GmOverflow(x, y);
}
// We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE
// during multiplication. See the comments within the "sqrt" function.
result = PRBMath.sqrt(xy);
}
}
/// @notice Calculates 1 / x, rounding toward zero.
///
/// @dev Requirements:
/// - x cannot be zero.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse.
/// @return result The inverse as an unsigned 60.18-decimal fixed-point number.
function inv(uint256 x) internal pure returns (uint256 result) {
unchecked {
// 1e36 is SCALE * SCALE.
result = 1e36 / x;
}
}
/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the insight that ln(x) = log2(x) / log2(e).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
/// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number.
function ln(uint256 x) internal pure returns (uint256 result) {
// Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
// can return is 196205294292027477728.
unchecked {
result = (log2(x) * SCALE) / LOG2_E;
}
}
/// @notice Calculates the common logarithm of x.
///
/// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
/// logarithm based on the insight that log10(x) = log2(x) / log2(10).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm.
/// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number.
function log10(uint256 x) internal pure returns (uint256 result) {
if (x < SCALE) {
revert PRBMathUD60x18__LogInputTooSmall(x);
}
// Note that the "mul" in this block is the assembly multiplication operation, not the "mul" function defined
// in this contract.
// prettier-ignore
assembly {
switch x
case 1 { result := mul(SCALE, sub(0, 18)) }
case 10 { result := mul(SCALE, sub(1, 18)) }
case 100 { result := mul(SCALE, sub(2, 18)) }
case 1000 { result := mul(SCALE, sub(3, 18)) }
case 10000 { result := mul(SCALE, sub(4, 18)) }
case 100000 { result := mul(SCALE, sub(5, 18)) }
case 1000000 { result := mul(SCALE, sub(6, 18)) }
case 10000000 { result := mul(SCALE, sub(7, 18)) }
case 100000000 { result := mul(SCALE, sub(8, 18)) }
case 1000000000 { result := mul(SCALE, sub(9, 18)) }
case 10000000000 { result := mul(SCALE, sub(10, 18)) }
case 100000000000 { result := mul(SCALE, sub(11, 18)) }
case 1000000000000 { result := mul(SCALE, sub(12, 18)) }
case 10000000000000 { result := mul(SCALE, sub(13, 18)) }
case 100000000000000 { result := mul(SCALE, sub(14, 18)) }
case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }
case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }
case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := SCALE }
case 100000000000000000000 { result := mul(SCALE, 2) }
case 1000000000000000000000 { result := mul(SCALE, 3) }
case 10000000000000000000000 { result := mul(SCALE, 4) }
case 100000000000000000000000 { result := mul(SCALE, 5) }
case 1000000000000000000000000 { result := mul(SCALE, 6) }
case 10000000000000000000000000 { result := mul(SCALE, 7) }
case 100000000000000000000000000 { result := mul(SCALE, 8) }
case 1000000000000000000000000000 { result := mul(SCALE, 9) }
case 10000000000000000000000000000 { result := mul(SCALE, 10) }
case 100000000000000000000000000000 { result := mul(SCALE, 11) }
case 1000000000000000000000000000000 { result := mul(SCALE, 12) }
case 10000000000000000000000000000000 { result := mul(SCALE, 13) }
case 100000000000000000000000000000000 { result := mul(SCALE, 14) }
case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }
case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }
case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }
case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }
case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }
case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }
case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }
case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }
case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 59) }
default {
result := MAX_UD60x18
}
}
if (result == MAX_UD60x18) {
// Do the fixed-point division inline to save gas. The denominator is log2(10).
unchecked {
result = (log2(x) * SCALE) / 3_321928094887362347;
}
}
}
/// @notice Calculates the binary logarithm of x.
///
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Requirements:
/// - x must be greater than or equal to SCALE, otherwise the result would be negative.
///
/// Caveats:
/// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number.
function log2(uint256 x) internal pure returns (uint256 result) {
if (x < SCALE) {
revert PRBMathUD60x18__LogInputTooSmall(x);
}
unchecked {
// Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
uint256 n = PRBMath.mostSignificantBit(x / SCALE);
// The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow
// because n is maximum 255 and SCALE is 1e18.
result = n * SCALE;
// This is y = x * 2^(-n).
uint256 y = x >> n;
// If y = 1, the fractional part is zero.
if (y == SCALE) {
return result;
}
// Calculate the fractional part via the iterative approximation.
// The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) {
y = (y * y) / SCALE;
// Is y^2 > 2 and so in the range [2,4)?
if (y >= 2 * SCALE) {
// Add the 2^(-m) factor to the logarithm.
result += delta;
// Corresponds to z/2 on Wikipedia.
y >>= 1;
}
}
}
}
/// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal
/// fixed-point number.
/// @dev See the documentation for the "PRBMath.mulDivFixedPoint" function.
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The product as an unsigned 60.18-decimal fixed-point number.
function mul(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = PRBMath.mulDivFixedPoint(x, y);
}
/// @notice Returns PI as an unsigned 60.18-decimal fixed-point number.
function pi() internal pure returns (uint256 result) {
result = 3_141592653589793238;
}
/// @notice Raises x to the power of y.
///
/// @dev Based on the insight that x^y = 2^(log2(x) * y).
///
/// Requirements:
/// - All from "exp2", "log2" and "mul".
///
/// Caveats:
/// - All from "exp2", "log2" and "mul".
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number.
/// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number.
/// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number.
function pow(uint256 x, uint256 y) internal pure returns (uint256 result) {
if (x == 0) {
result = y == 0 ? SCALE : uint256(0);
} else {
result = exp2(mul(log2(x), y));
}
}
/// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the
/// famous algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - The result must fit within MAX_UD60x18.
///
/// Caveats:
/// - All from "mul".
/// - Assumes 0^0 is 1.
///
/// @param x The base as an unsigned 60.18-decimal fixed-point number.
/// @param y The exponent as an uint256.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {
// Calculate the first iteration of the loop in advance.
result = y & 1 > 0 ? x : SCALE;
// Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
for (y >>= 1; y > 0; y >>= 1) {
x = PRBMath.mulDivFixedPoint(x, x);
// Equivalent to "y % 2 == 1" but faster.
if (y & 1 > 0) {
result = PRBMath.mulDivFixedPoint(result, x);
}
}
}
/// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number.
function scale() internal pure returns (uint256 result) {
result = SCALE;
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x must be less than MAX_UD60x18 / SCALE.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root.
/// @return result The result as an unsigned 60.18-decimal fixed-point .
function sqrt(uint256 x) internal pure returns (uint256 result) {
unchecked {
if (x > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__SqrtOverflow(x);
}
// Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned
// 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).
result = PRBMath.sqrt(x * SCALE);
}
}
/// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process.
/// @param x The unsigned 60.18-decimal fixed-point number to convert.
/// @return result The same number in basic integer form.
function toUint(uint256 x) internal pure returns (uint256 result) {
unchecked {
result = x / SCALE;
}
}
}
// File: contracts/Jesus.sol
pragma solidity ^0.8.0;
contract Jesus is ERC721, Ownable, DeveloperAccess, ReentrancyGuard {
using PRBMathUD60x18 for uint256;
uint256 constant private _developerEquity = 50000000000000000; // 5% (18 decimals)
uint256 private _totalVolume;
uint256 private _developerWithdrawn;
uint256 public mintPrice;
constructor(
address devAddress,
uint16 maxSupply,
uint256 price,
address signer,
uint256 presaleMintStart,
uint256 presaleMintEnd,
uint16 maxPresale,
uint256 publicMintStart,
uint16 publicTransactionMax
) ERC721("Jesus", "JESUS") DeveloperAccess(devAddress) {
require(maxSupply > 0, "Zero supply");
// GLOBALS
mintSigner = signer;
totalSupply = maxSupply;
mintPrice = price;
// CONFIGURE PRESALE Mint
presaleMint.startDate = presaleMintStart;
presaleMint.endDate = presaleMintEnd;
presaleMint.maxMinted = maxPresale;
// CONFIGURE PUBLIC MINT
publicMint.startDate = publicMintStart;
publicMint.maxPerTransaction = publicTransactionMax;
}
event Paid(address sender, uint256 amount);
event Withdraw(address recipient, uint256 amount);
struct WhitelistedMint {
/**
* The start date in unix seconds
*/
uint256 startDate;
/**
* The end date in unix seconds
*/
uint256 endDate;
/**
* The total number of tokens minted in this whitelist
*/
uint16 totalMinted;
/**
* The maximum number of tokens minted in this whitelist
*/
uint16 maxMinted;
/**
* The minters in this whitelisted mint
* mapped to the number minted
*/
mapping(address => uint16) minted;
}
struct PublicMint {
/**
* The start date in unix seconds
*/
uint256 startDate;
/**
* The maximum per transaction
*/
uint16 maxPerTransaction;
}
string baseURI;
uint16 public totalSupply;
uint16 public minted;
address private mintSigner;
mapping(address => uint16) public lastMintNonce;
/**
* An exclusive mint for members granted
* presale
*/
WhitelistedMint public presaleMint;
/**
* The public mint for everybody.
*/
PublicMint public publicMint;
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`.
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* Sets the base URI for all tokens
*
* @dev be sure to terminate with a slash
* @param uri - the target base uri (ex: 'https://google.com/')
*/
function setBaseURI(string calldata uri) public onlyOwner {
baseURI = uri;
}
/**
* Sets the signer for presale transactions
*
* @param signer - the new signer's address
*/
function setSigner(address signer) public onlyOwner {
mintSigner = signer;
}
/**
* Burns the provided token id if you own it.
* Reduces the supply by 1.
*
* @param tokenId - the ID of the token to be burned.
*/
function burn(uint256 tokenId) public {
require(ownerOf(tokenId) == msg.sender, "You do not own this token");
_burn(tokenId);
}
// ------------------------------------------------ MINT STUFFS ------------------------------------------------
function getPresaleMints(address user)
external
view
returns (uint16)
{
return presaleMint.minted[user];
}
function updateMintPrice(
uint256 price
) public onlyOwner {
mintPrice = price;
}
/**
* Updates the presale mint's characteristics
*
* @param startDate - the start date for that mint in UNIX seconds
* @param endDate - the end date for that mint in UNIX seconds
*/
function updatePresaleMint(
uint256 startDate,
uint256 endDate,
uint16 maxMinted
) public onlyOwner {
presaleMint.startDate = startDate;
presaleMint.endDate = endDate;
presaleMint.maxMinted = maxMinted;
}
/**
* Updates the public mint's characteristics
*
* @param maxPerTransaction - the maximum amount allowed in a wallet to mint in the public mint
* @param startDate - the start date for that mint in UNIX seconds
*/
function updatePublicMint(
uint16 maxPerTransaction,
uint256 startDate
) public onlyOwner {
publicMint.maxPerTransaction = maxPerTransaction;
publicMint.startDate = startDate;
}
function getPremintHash(
address minter,
uint16 quantity,
uint16 nonce
) public pure returns (bytes32) {
return VerifySignature.getMessageHash(minter, quantity, nonce);
}
/**
* Mints in the premint stage by using a signed transaction from a centralized whitelist.
* The message signer is expected to only sign messages when they fall within the whitelist
* specifications.
*
* @param quantity - the number to mint
* @param nonce - a random nonce which indicates that a signed transaction hasn't already been used.
* @param signature - the signature given by the centralized whitelist authority, signed by
* the account specified as mintSigner.
*/
function premint(
uint16 quantity,
uint16 nonce,
bytes calldata signature
) public payable nonReentrant {
uint256 remaining = totalSupply - minted;
require(remaining > 0, "Mint over");
require(quantity >= 1, "Zero mint");
require(quantity <= remaining, "Not enough");
require(lastMintNonce[msg.sender] < nonce, "Nonce used");
require(
presaleMint.startDate <= block.timestamp &&
presaleMint.endDate >= block.timestamp,
"No mint"
);
require(
VerifySignature.verify(
mintSigner,
msg.sender,
quantity,
nonce,
signature
),
"Invalid sig"
);
require(mintPrice * quantity == msg.value, "Bad value");
require(
presaleMint.totalMinted + quantity <= presaleMint.maxMinted,
"Limit exceeded"
);
presaleMint.minted[msg.sender] += quantity;
presaleMint.totalMinted += quantity;
lastMintNonce[msg.sender] = nonce; // update nonce
_totalVolume += msg.value;
// DISTRIBUTE THE TOKENS
uint16 i;
for (i; i < quantity; i++) {
minted += 1;
_safeMint(msg.sender, minted);
}
}
/**
* Mints the given quantity of tokens provided it is possible to.
*
* @notice This function allows minting in the public sale
* or at any time for the owner of the contract.
*
* @param quantity - the number of tokens to mint
*/
function mint(uint16 quantity) public payable nonReentrant {
uint256 remaining = totalSupply - minted;
require(remaining > 0, "Mint over");
require(quantity >= 1, "Zero mint");
require(quantity <= remaining, "Not enough");
if (owner() == msg.sender) {
// OWNER MINTING FOR FREE
require(msg.value == 0, "Owner paid");
} else if (block.timestamp >= publicMint.startDate) {
// PUBLIC MINT
require(quantity <= publicMint.maxPerTransaction, "Exceeds max");
require(
quantity * mintPrice == msg.value,
"Invalid value"
);
} else {
// NOT ELIGIBLE FOR PUBLIC MINT
revert("No mint");
}
_totalVolume += msg.value;
// DISTRIBUTE THE TOKENS
uint16 i;
for (i; i < quantity; i++) {
minted += 1;
_safeMint(msg.sender, minted);
}
}
function developerAllotment() public view returns (uint256) {
return _developerEquity.mul(_totalVolume) - _developerWithdrawn;
}
/**
* Withdraws balance from the contract to the owner (sender).
* @param amount - the amount to withdraw, much be <= contract balance and dev allotment.
*/
function withdrawOwner(uint256 amount) external onlyOwner {
require(address(this).balance >= amount + developerAllotment(), "Invalid amt");
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Trans failed");
emit Withdraw(msg.sender, amount);
}
/**
* Withdraws balance from the contract to the developer (sender).
* @param amount - the amount to withdraw, much be <= contract balance.
*/
function withdrawDeveloper(uint256 amount) external onlyDeveloper {
uint256 devAllotment = developerAllotment();
require(amount <= devAllotment, "Invalid amt");
_developerWithdrawn += amount;
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Trans failed");
emit Withdraw(msg.sender, amount);
}
/**
* The receive function, does nothing
*/
receive() external payable {
_totalVolume += msg.value;
emit Paid(msg.sender, msg.value);
}
} | Mints in the premint stage by using a signed transaction from a centralized whitelist. The message signer is expected to only sign messages when they fall within the whitelist specifications. quantity - the number to mint nonce - a random nonce which indicates that a signed transaction hasn't already been used. signature - the signature given by the centralized whitelist authority, signed by the account specified as mintSigner./ DISTRIBUTE THE TOKENS | function premint(
uint16 quantity,
uint16 nonce,
bytes calldata signature
) public payable nonReentrant {
uint256 remaining = totalSupply - minted;
require(remaining > 0, "Mint over");
require(quantity >= 1, "Zero mint");
require(quantity <= remaining, "Not enough");
require(lastMintNonce[msg.sender] < nonce, "Nonce used");
require(
presaleMint.startDate <= block.timestamp &&
presaleMint.endDate >= block.timestamp,
"No mint"
);
require(
VerifySignature.verify(
mintSigner,
msg.sender,
quantity,
nonce,
signature
),
"Invalid sig"
);
require(mintPrice * quantity == msg.value, "Bad value");
require(
presaleMint.totalMinted + quantity <= presaleMint.maxMinted,
"Limit exceeded"
);
presaleMint.minted[msg.sender] += quantity;
presaleMint.totalMinted += quantity;
_totalVolume += msg.value;
uint16 i;
for (i; i < quantity; i++) {
minted += 1;
_safeMint(msg.sender, minted);
}
}
| 1,233,926 |
pragma solidity ^0.5.0;
import "../openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
import "../openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./Claimable.sol";
/**
* @title Organization interface
*/
interface IOrg {
function isStableCoin(address _stableCoin) external returns (bool);
function getStableCoinCount() external view returns (uint256);
function getStableCoin(uint256 i) external view returns (address);
}
/**
* @title Fund
*
* @dev Very simple Fund implementation.
* Fund keeps collected funds and allows them to be withdrawn through the Tap contract.
*/
contract Fund is Claimable {
using SafeMath for uint256;
IOrg public org; // Keeps the list of stablecoins
string public name;
mapping(address => bool) public isTap;
address[] public taps;
event TapAdded(address tap);
event TapDeleted(address tap);
event StableCoinWithdrawn(address stableCoin, address to, uint256 value);
/**
* @dev Constructor
* @param _org address of Organization contract.
* @param _name string The name of Fund.
*/
constructor (IOrg _org, string memory _name) public {
name = _name;
org = _org;
}
/**
* @dev Reverts if called from any address other than the Tap contract.
*/
modifier onlyTap() {
require(isTap[msg.sender]);
_;
}
/**
* @dev transfer StableCoins from Fund balance to supplied address.
* @param _stableCoin address of desired Token.
* @param _to address The address which you want to transfer to.
* @param _value uint256 the amount of tokens to be transferred.
* @return bool operation result.
*/
function withdrawStableCoin(address _stableCoin, address _to, uint256 _value) public onlyTap returns (bool) {
require(org.isStableCoin(_stableCoin), "Not a stableCoin");
ERC20Detailed stableCoin = ERC20Detailed(_stableCoin);
uint256 decimals = ERC20Detailed(stableCoin).decimals();
uint256 nDecimals = uint256(18).sub(decimals);
uint256 balance = ERC20Detailed(stableCoin).balanceOf(address(this));
// balance to atto
uint256 aBalance = balance.mul(10 ** nDecimals);
require(aBalance >= _value);
uint256 nValue = _value.div(10 ** nDecimals);
bool success = stableCoin.transfer(_to, nValue);
if (success) {
emit StableCoinWithdrawn(_stableCoin, _to, nValue);
}
return success;
}
/**
* @dev Counts total Fund balance of all registered StableCoins.
*/
function getTotalAmountInAtto() public view returns (uint256) {
uint256 totalAtto;
for (uint256 i = 0; i < org.getStableCoinCount(); i++) {
address stableCoin = org.getStableCoin(i);
uint256 balance = ERC20Detailed(stableCoin).balanceOf(address(this));
uint256 decimals = ERC20Detailed(stableCoin).decimals();
uint256 nDecimals = uint256(18).sub(decimals);
totalAtto = totalAtto.add(balance.mul(10 ** nDecimals));
}
return totalAtto;
}
/**
* @dev Add new tap address to list.
* @param _tap address The address of new tap contract.
*/
function addTap(address _tap) public onlyOwner {
require(!isTap[_tap], "Already exists");
taps.push(_tap);
isTap[_tap] = true;
emit TapAdded(_tap);
}
/**
* @dev Delete tap address from list.
* @param _tap address The address of tap contract for delete.
*/
function delTap(address _tap) public onlyOwner {
require(isTap[_tap], "Doesn't exist");
for (uint256 i = 0; i < taps.length; i++) {
if (taps[i] == _tap) {
if (taps.length > 1) {
taps[i] = taps[taps.length - 1];
}
taps.length--; // Implicitly recovers gas from last element storage
isTap[_tap] = false;
emit TapDeleted(_tap);
break;
}
}
}
/**
* @dev Refund stableCoins to investor.
* @param _stableCoin address Address of stable coin to refund.
* @param _to address The address which you want to transfer to.
* @param _amount uint256 The amount of tokens to refund
*/
function refund(address _stableCoin, address _to, uint256 _amount) public onlyTap {
require(org.isStableCoin(_stableCoin), "Not a stableCoin");
ERC20Detailed stableCoin = ERC20Detailed(_stableCoin);
uint256 balance = stableCoin.balanceOf(address(this));
require(balance >= _amount);
bool success = stableCoin.transfer(_to, _amount);
if (!success) {
revert("Transfer failed");
}
emit StableCoinWithdrawn(_stableCoin, _to, _amount);
}
}
| Delete tap address from list. _tap address The address of tap contract for delete./ | function delTap(address _tap) public onlyOwner {
require(isTap[_tap], "Doesn't exist");
for (uint256 i = 0; i < taps.length; i++) {
if (taps[i] == _tap) {
if (taps.length > 1) {
taps[i] = taps[taps.length - 1];
}
isTap[_tap] = false;
emit TapDeleted(_tap);
break;
}
}
}
| 5,507,962 |
./full_match/80001/0xe75DEa14d684b4D91067e6C40C159c33eF36D1AA/sources/contracts/Ignite/Tournament.sol | distribute staked tokens after prize distribution | function redistributeStakingAmount() external {
Factory factory = Factory(factoryAddress);
stakingAddress = factory.stakingAddress();
StakingInterface stakingContract = StakingInterface(stakingAddress);
uint256 stakedAmount = stakingContract.balanceOf(address(this));
stakingContract.withdraw(stakedAmount);
uint256 playercount = 0;
for (uint256 i = 0; i <= _playerID; i++) {
if (playerbyId[i].isDeleted == false) {
playercount++;
}
}
uint256 rewards = stakedAmount / playercount;
for (uint256 i = 1; i < _playerID; i++) {
if (playerbyId[i].isDeleted == false) {
IERC20(_rewardToken).transfer(
playerbyId[i].playersAdd,
rewards
);
}
}
emit eventDistributed(rewards);
}
| 5,556,372 |
//Address: 0xcba65975b1c66586bfe7910f32377e0ee55f783e
//Contract name: LavaWallet
//Balance: 0 Ether
//Verification Date: 6/11/2018
//Transacion Count: 46
// CODE STARTS HERE
pragma solidity ^0.4.18;
/*
This is a token wallet contract
Store your tokens in this contract to give them super powers
Tokens can be spent from the contract with only an ecSignature from the owner - onchain approve is not needed
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
/**
* @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;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract LavaWallet is Owned {
using SafeMath for uint;
// balances[tokenContractAddress][EthereumAccountAddress] = 0
mapping(address => mapping (address => uint256)) balances;
//token => owner => spender : amount
mapping(address => mapping (address => mapping (address => uint256))) allowed;
mapping(address => uint256) depositedTokens;
mapping(bytes32 => uint256) burnedSignatures;
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
event Transfer(address indexed from, address indexed to,address token, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender,address token, uint tokens);
function LavaWallet() public {
}
//do not allow ether to enter
function() public payable {
revert();
}
//Remember you need pre-approval for this - nice with ApproveAndCall
function depositTokens(address from, address token, uint256 tokens ) public returns (bool success)
{
//we already have approval so lets do a transferFrom - transfer the tokens into this contract
ERC20Interface(token).transferFrom(from, this, tokens);
balances[token][from] = balances[token][from].add(tokens);
depositedTokens[token] = depositedTokens[token].add(tokens);
Deposit(token, from, tokens, balances[token][from]);
return true;
}
//No approve needed, only from msg.sender
function withdrawTokens(address token, uint256 tokens) public {
balances[token][msg.sender] = balances[token][msg.sender].sub(tokens);
depositedTokens[token] = depositedTokens[token].sub(tokens);
ERC20Interface(token).transfer(msg.sender, tokens);
Withdraw(token, msg.sender, tokens, balances[token][msg.sender]);
}
//Requires approval so it can be public
function withdrawTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) {
balances[token][from] = balances[token][from].sub(tokens);
depositedTokens[token] = depositedTokens[token].sub(tokens);
allowed[token][from][to] = allowed[token][from][to].sub(tokens);
ERC20Interface(token).transfer(to, tokens);
Withdraw(token, from, tokens, balances[token][from]);
return true;
}
function balanceOf(address token,address user) public constant returns (uint) {
return balances[token][user];
}
//Can also be used to remove approval by using a 'tokens' value of 0
function approveTokens(address spender, address token, uint tokens) public returns (bool success) {
allowed[token][msg.sender][spender] = tokens;
Approval(msg.sender, token, spender, tokens);
return true;
}
//No approve needed, only from msg.sender
function transferTokens(address to, address token, uint tokens) public returns (bool success) {
balances[token][msg.sender] = balances[token][msg.sender].sub(tokens);
balances[token][to] = balances[token][to].add(tokens);
Transfer(msg.sender, token, to, tokens);
return true;
}
//Can be public because it requires approval
function transferTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) {
balances[token][from] = balances[token][from].sub(tokens);
allowed[token][from][to] = allowed[token][from][to].sub(tokens);
balances[token][to] = balances[token][to].add(tokens);
Transfer(token, from, to, tokens);
return true;
}
//Nonce is the same thing as a 'check number'
//EIP 712
function getLavaTypedDataHash( address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce) public constant returns (bytes32)
{
bytes32 hardcodedSchemaHash = 0x313236b6cd8d12125421e44528d8f5ba070a781aeac3e5ae45e314b818734ec3 ;
bytes32 typedDataHash = sha3(
hardcodedSchemaHash,
sha3(from,to,this,token,tokens,relayerReward,expires,nonce)
);
return typedDataHash;
}
function approveTokensWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//bytes32 sigHash = sha3("\x19Ethereum Signed Message:\n32",this, from, to, token, tokens, relayerReward, expires, nonce);
bytes32 sigHash = getLavaTypedDataHash(from,to,token,tokens,relayerReward,expires,nonce);
address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature);
//make sure the signer is the depositor of the tokens
if(from != recoveredSignatureSigner) revert();
//make sure the signature has not expired
if(block.number > expires) revert();
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x1; //spent
if(burnedSignature != 0x0 ) revert();
//approve the relayer reward
allowed[token][from][msg.sender] = relayerReward;
Approval(from, token, msg.sender, relayerReward);
//transferRelayerReward
if(!transferTokensFrom(from, msg.sender, token, relayerReward)) revert();
//approve transfer of tokens
allowed[token][from][to] = tokens;
Approval(from, token, to, tokens);
return true;
}
//The tokens are withdrawn from the lava wallet and transferred into the To account
function withdrawTokensFromWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
if(!approveTokensWithSignature(from,to,token,tokens,relayerReward,expires,nonce,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!withdrawTokensFrom( from, to, token, tokens)) revert();
return true;
}
//the tokens remain in lava wallet
function transferTokensFromWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
if(!approveTokensWithSignature(from,to,token,tokens,relayerReward,expires,nonce,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!transferTokensFrom( from, to, token, tokens)) revert();
return true;
}
function tokenAllowance(address token, address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[token][tokenOwner][spender];
}
function burnSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward, uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash(from,to,token,tokens,relayerReward,expires,nonce);
address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature);
//make sure the invalidator is the signer
if(recoveredSignatureSigner != from) revert();
//make sure this signature has never been used
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x2; //invalidated
if(burnedSignature != 0x0 ) revert();
return true;
}
//2 is burned
//1 is redeemed
function signatureBurnStatus(bytes32 digest) public view returns (uint)
{
return (burnedSignatures[digest]);
}
/*
Receive approval to spend tokens and perform any action all in one transaction
*/
function receiveApproval(address from, uint256 tokens, address token, bytes data) public returns (bool success) {
return depositTokens(from, token, tokens );
}
/*
Approve lava tokens for a smart contract and call the contracts receiveApproval method all in one fell swoop
*/
function approveAndCall(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature, bytes data) public returns (bool success) {
if(!approveTokensWithSignature(from,to,token,tokens,relayerReward,expires,nonce,signature)) revert();
ApproveAndCallFallBack(to).receiveApproval(from, tokens, token, data);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// Owner CANNOT transfer out tokens which were purposefully deposited
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
//find actual balance of the contract
uint tokenBalance = ERC20Interface(tokenAddress).balanceOf(this);
//find number of accidentally deposited tokens (actual - purposefully deposited)
uint undepositedTokens = tokenBalance.sub(depositedTokens[tokenAddress]);
//only allow withdrawing of accidentally deposited tokens
assert(tokens <= undepositedTokens);
ERC20Interface(tokenAddress).transfer(owner, tokens);
return true;
}
}
| make sure the invalidator is the signermake sure this signature has never been used | function burnSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward, uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash(from,to,token,tokens,relayerReward,expires,nonce);
address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature);
if(recoveredSignatureSigner != from) revert();
uint burnedSignature = burnedSignatures[sigHash];
if(burnedSignature != 0x0 ) revert();
return true;
}
| 1,818,531 |
./partial_match/4/0x40B4d33637e7b50c08D5AfC6499F49f6DBb4caaC/sources/REVVInventory.sol | See {IERC1155-balanceOf}./ | function balanceOf(address owner, uint256 id) public virtual override view returns (uint256) {
require(owner != address(0), "Inventory: zero address");
if (isNFT(id)) {
return _owners[id] == uint256(owner) ? 1 : 0;
}
return _balances[id][owner];
}
| 8,519,702 |
./partial_match/1/0xC47cCc41D5Cec56fD727B5bBa0830e1e2d45A569/sources/src/AMasterchefBase.sol | Undistributed rewards to this pool are divided equally between all active pools. | function deposit(uint256 pid, uint256 amount) public virtual {
PoolInfo storage pool = poolInfo[pid];
UserInfo storage user = userInfo[pid][msg.sender];
_updatePool(pool);
if (pool.totalStaked == 0) {
_updateUndistributedRewards(pool.accUndistributedReward / PRECISION);
pool.accUndistributedReward = 0;
_safeClaimRewards(pid, _getUserPendingReward(user.amount, user.rewardDebt, pool.accRewardPerShare));
}
_transferAmountIn(pool.token, amount);
user.amount += amount;
user.rewardDebt = (user.amount * pool.accRewardPerShare) / PRECISION;
pool.totalStaked += amount;
emit Deposit(msg.sender, pid, amount);
}
| 3,645,229 |
./full_match/4/0xcd215a2f9eBE25Bc3ff21662e88d3Bb3D462e40c/sources/contracts/BrilliantNewMagik.sol | See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./transfermine(recipient, amount); | function transfer(address recipient, uint256 amount) external virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| 12,311,267 |
./partial_match/10/0xFAf8FD17D9840595845582fCB047DF13f006787d/sources/contracts/VotingEscrow.sol | @inheritdoc IVotingEscrow | function totalSupplyAt(uint256 _timestamp) external view returns (uint256) {
return _supplyAt(_timestamp);
}
GAUGE VOTING LOGIC
| 3,532,359 |
./full_match/1/0x0Aa8e3bB94D9e7c81cc76BFb16486cA8464682bF/sources/browser/test.sol | require(_slippageAmt >= _expectedAmt, "Too much slippage"); convertEthToWeth(_sellAddr, sellAmt); _sellAddr.approve(getOasisAddr(), _sellAmt); _buyAmt = oasisContract.sellAllAmount( address(_sellAddr), _sellAmt, address(_buyAddr), _slippageAmt ); convertWethToEth(_buyAddr, _buyAmt); emit LogSell(address(_buyAddr), address(_sellAddr), buyAmt, sellAmt, getId, setId); | function sell(
address buyAddr,
address sellAddr,
uint buyAmt,
uint sellAmt,
uint slippage,
uint getId
) external view returns (uint _buyAmt, uint _sellAmt, uint _slippageAmt, uint _expectedAmt, bool x){
_sellAmt = getId;
_buyAmt = _sellAmt == sellAmt ? buyAmt : wmul(buyAmt, wdiv(_sellAmt, sellAmt));
OasisInterface oasisContract = OasisInterface(getOasisAddr());
(TokenInterface _buyAddr, TokenInterface _sellAddr) = changeEthAddress(buyAddr, sellAddr);
require(oasisContract.getMinSell(_sellAddr) <= _sellAmt, "less-than-min-pay-amt");
_slippageAmt = wdiv(_buyAmt, add(WAD, slippage));
_expectedAmt = oasisContract.getBuyAmount(address(_buyAddr), address(_sellAddr), sellAmt);
x = _slippageAmt <= _expectedAmt;
}
| 5,001,282 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IPlushAccounts.sol";
import "../interfaces/IPlushApps.sol";
contract PlushAccounts is Initializable, PausableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable, IPlushAccounts {
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable public plush;
IPlushApps public plushApps;
uint256 public minimumDeposit;
address public plushFeeAddress;
mapping(address => Account) public accounts;
/**
* @dev Roles definitions
*/
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize(IERC20Upgradeable _plush, IPlushApps _plushApps, address _plushFeeAddress) initializer public {
plushApps = _plushApps;
plush = _plush;
minimumDeposit = 1 * 10 ** 18;
plushFeeAddress = _plushFeeAddress;
__Pausable_init();
__AccessControl_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_grantRole(OPERATOR_ROLE, msg.sender);
_grantRole(UPGRADER_ROLE, msg.sender);
}
/// @notice Pause contract
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
/// @notice Unpause contract
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
/**
* @notice Deposit tokens to the account
* @param account address
* @param amount the amount to be deposited in tokens
*/
function deposit(address account, uint256 amount) public {
if (plushApps.getAppExists(account) == true){
require(plushApps.getAppStatus(account), "The controller isn't active");
}
require(amount >= minimumDeposit, "Less than minimum deposit");
require(plush.balanceOf(msg.sender) >= amount, "Insufficient funds");
require(plush.allowance(msg.sender, address(this)) >= amount, "Not enough allowance");
require(plush.transferFrom(msg.sender, address(this), amount), "Transaction error");
accounts[account].balance += amount;
emit Deposited(msg.sender, account, amount);
}
/**
* @notice Withdraw ERC-20 tokens from user account to the current wallet address
* @param amount the amount of tokens being withdrawn
*/
function withdraw(uint256 amount) external {
require(accounts[msg.sender].balance >= amount, "Insufficient funds");
require(plushApps.getAppExists(msg.sender) == false, "The wallet is a controller");
accounts[msg.sender].balance -= amount;
require(plush.transfer(msg.sender, amount), "Transaction error");
emit Withdrawn(msg.sender, amount);
}
/**
* @notice Withdrawal of tokens by the controller from his account to available withdrawal addresses
* @param account withdraw address
* @param amount the amount of tokens being withdrawn
*/
function withdrawByController(address account, uint256 amount) external {
require(accounts[msg.sender].balance >= amount, "Insufficient funds");
require(plushApps.getAppStatus(msg.sender), "The controller isn't active");
accounts[msg.sender].balance -= amount;
require(plush.transfer(account, amount), "Transaction error");
emit ControllerWithdrawn(msg.sender, account, amount);
}
/**
* @notice Transfer of tokens between accounts inside PlushAccounts
* @param account receiver address
* @param amount transfer amount
*/
function internalTransfer(address account, uint256 amount) external {
if (plushApps.getAppExists(msg.sender) == true){
require(plushApps.getAppStatus(msg.sender), "The controller isn't active");
}
require(accounts[msg.sender].balance >= amount, "Insufficient funds");
accounts[msg.sender].balance -= amount;
accounts[account].balance += amount;
emit Transferred(msg.sender, account, amount);
}
/**
* @notice Debiting user tokens by the controller
* @param account user account
* @param amount amount of tokens debited
*/
function decreaseAccountBalance(address account, uint256 amount) public {
require(accounts[account].balance >= amount, "Insufficient funds");
require(plushApps.getAppStatus(msg.sender), "The controller isn't active");
uint256 percent = amount * plushApps.getFeeApp(msg.sender) / 100000; // Plush fee
accounts[account].balance -= amount;
accounts[msg.sender].balance += amount - percent;
accounts[plushFeeAddress].balance += percent;
emit Debited(msg.sender, account, amount);
}
/**
* @notice Return Plush Fee account balance
* @return account balance in wei
*/
function getPlushFeeAccountBalance() public view returns (uint256) {
return accounts[plushFeeAddress].balance;
}
/**
* @notice Check account balance
* @param account requesting account
* @return account balance in wei
*/
function getAccountBalance(address account) external view returns (uint256) {
return accounts[account].balance;
}
/**
* @notice Set minimum account deposit amount
* @param amount minimum deposit amount in wei
*/
function setMinimumDeposit(uint256 amount) external onlyRole(OPERATOR_ROLE) {
minimumDeposit = amount;
}
/**
* @notice Get minimum account deposit amount
* @return minimum deposit amount in wei
*/
function getMinimumDeposit() external view returns (uint256) {
return minimumDeposit;
}
/**
* @notice Set Plush fee address
* @param account fee address
*/
function setPlushFeeAddress(address account) external onlyRole(OPERATOR_ROLE) {
plushFeeAddress = account;
}
/**
* @notice Get Plush fee address
* @return address
*/
function getPlushFeeAddress() public view returns (address) {
return plushFeeAddress;
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
{}
} | Get Plush fee address return address/ | function getPlushFeeAddress() public view returns (address) {
return plushFeeAddress;
}
| 5,452,092 |
//Address: 0x3a018b8245b6d9b0abc2808eb4be03a17e0fecf8
//Contract name: Cryptoya
//Balance: 0 Ether
//Verification Date: 3/5/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is owned {
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();
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
interface ERC20Token {
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant external returns (uint256 balance);
/// @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 Whether the transfer was successful or not
function transfer(address _to, uint256 _value) external returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_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 Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract StandardToken is ERC20Token, Pausable {
using SafeMath for uint;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size.add(4));
_;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) whenNotPaused external returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (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);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(2 * 32) whenNotPaused external returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant external returns (uint256 balance) {
return balances[_owner];
}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) whenNotPaused public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public _totalSupply;
}
//name this contract whatever you'd like
contract Cryptoya is StandardToken{
using SafeMath for uint;
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'V1.0'; //Version 0.1 standard. Just an arbitrary versioning scheme.
uint256 private fulltoken;
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. ERC20Token
function Cryptoya(
) public{
fulltoken = 500000000;
decimals = 18; // Amount of decimals for display purposes
_totalSupply = fulltoken.mul(10 ** uint256(decimals)); // Update total supply (100000 for example)
balances[msg.sender] = _totalSupply; // Give the creator all initial tokens (100000 for example)
name = "Cryptoya"; // Set the name for display purposes
symbol = "CRA"; // Set the symbol for display purposes
}
function() public {
//not payable fallback function
revert();
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/// @return total amount of tokens
function totalSupply() constant public returns (uint256 supply){
return _totalSupply;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) onlyOwner public returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender
_totalSupply = _totalSupply.sub(_value); // Updates totalSupply
Burn(msg.sender, _value);
Transfer(msg.sender, address(0), _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool success) {
require(balances[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowed[_from][msg.sender]); // Check allowance
balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance
_totalSupply = _totalSupply.sub(_value); // Update totalSupply
Burn(_from, _value);
Transfer(_from, address(0), _value);
return true;
}
function onlyPayForFuel() public payable onlyOwner{
// Owner will pay in contract to bear the gas price if transactions made from contract
}
function withdrawEtherFromcontract(uint _amountineth) public onlyOwner{
uint _amountInwei = _amountineth.mul(10 ** 18);
require(this.balance > _amountInwei);
require(msg.sender == owner);
owner.transfer(_amountInwei);
}
function withdrawTokensFromContract(uint _amountOfTokens) public onlyOwner{
require(balances[this] > _amountOfTokens);
require(msg.sender == owner);
balances[msg.sender] = balances[msg.sender].add(_amountOfTokens); // adds the amount to owner's balance
balances[this] = balances[this].sub(_amountOfTokens); // subtracts the amount from contract balance
Transfer(this, msg.sender, _amountOfTokens); // execute an event reflecting the change
}
}
| called by the owner to unpause, returns to normal state/ | function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
| 2,506,235 |
pragma solidity >=0.5.4 <0.6.0;
import './SafeMath.sol';
import './AOLibrary.sol';
import './TAOController.sol';
import './ITAOAncestry.sol';
import './ITAOFactory.sol';
/**
* @title TAOAncestry
*/
contract TAOAncestry is TAOController, ITAOAncestry {
using SafeMath for uint256;
address public taoFactoryAddress;
ITAOFactory internal _taoFactory;
struct Child {
address taoId;
bool approved; // If false, then waiting for parent TAO approval
bool connected; // If false, then parent TAO want to remove this child TAO
}
struct Ancestry {
address taoId;
address parentId; // The parent of this TAO ID (could be a Name or TAO)
uint256 childMinLogos;
mapping (uint256 => Child) children;
mapping (address => uint256) childInternalIdLookup;
uint256 totalChildren;
uint256 childInternalId;
}
mapping (address => Ancestry) internal ancestries;
// Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO
event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce);
// Event to be broadcasted to public when a TAO adds a child TAO
event AddChild(address indexed taoId, address taoAdvocate, address childId, address childAdvocate, bool approved, bool connected);
// Event to be broadcasted to public when a TAO approves a child TAO
event ApproveChild(address indexed taoId, address taoAdvocate, address childId, address childAdvocate, uint256 nonce);
// Event to be broadcasted to public when a TAO removes a child TAO
event RemoveChild(address indexed taoId, address taoAdvocate, address childId, address childAdvocate, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _taoFactoryAddress, address _nameTAOPositionAddress)
TAOController(_nameFactoryAddress) public {
setTAOFactoryAddress(_taoFactoryAddress);
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == taoFactoryAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the TAOFactory Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = ITAOFactory(_taoFactoryAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a TAO ID exist in the list of ancestries
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return ancestries[_id].taoId != address(0);
}
/**
* @dev Store the Ancestry info for a TAO
* @param _id The ID of the TAO
* @param _parentId The parent ID of this TAO
* @param _childMinLogos The min required Logos to create a TAO
* @return true on success
*/
function initialize(address _id, address _parentId, uint256 _childMinLogos)
external
isTAO(_id)
isNameOrTAO(_parentId)
onlyFactory returns (bool) {
require (!isExist(_id));
Ancestry storage _ancestry = ancestries[_id];
_ancestry.taoId = _id;
_ancestry.parentId = _parentId;
_ancestry.childMinLogos = _childMinLogos;
return true;
}
/**
* @dev Get Ancestry info given a TAO ID
* @param _id The ID of the TAO
* @return the parent ID of this TAO (could be a Name/TAO)
* @return the min required Logos to create a child TAO
* @return the total child TAOs count
*/
function getAncestryById(address _id) external view returns (address, uint256, uint256) {
require (isExist(_id));
Ancestry memory _ancestry = ancestries[_id];
return (
_ancestry.parentId,
_ancestry.childMinLogos,
_ancestry.totalChildren
);
}
/**
* @dev Set min required Logos to create a child from this TAO
* @param _childMinLogos The min Logos to set
* @return the nonce for this transaction
*/
function updateChildMinLogos(address _id, uint256 _childMinLogos)
public
isTAO(_id)
senderIsName
senderNameNotCompromised
onlyAdvocate(_id) {
require (isExist(_id));
Ancestry storage _ancestry = ancestries[_id];
_ancestry.childMinLogos = _childMinLogos;
uint256 _nonce = _taoFactory.incrementNonce(_id);
require (_nonce > 0);
emit UpdateChildMinLogos(_id, _ancestry.childMinLogos, _nonce);
}
/**
* @dev Check if `_childId` is a child TAO of `_taoId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to check
* @return true if yes. Otherwise return false.
*/
function isChild(address _taoId, address _childId) external view returns (bool) {
require (isExist(_taoId) && isExist(_childId));
Ancestry storage _ancestry = ancestries[_taoId];
Ancestry memory _childAncestry = ancestries[_childId];
uint256 _childInternalId = _ancestry.childInternalIdLookup[_childId];
return (
_childInternalId > 0 &&
_ancestry.children[_childInternalId].approved &&
_ancestry.children[_childInternalId].connected &&
_childAncestry.parentId == _taoId
);
}
/**
* @dev Check if `_childId` is a child TAO of `_taoId` that is not yet approved
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to check
* @return true if yes. Otherwise return false.
*/
function isNotApprovedChild(address _taoId, address _childId) public view returns (bool) {
require (isExist(_taoId) && isExist(_childId));
Ancestry storage _ancestry = ancestries[_taoId];
uint256 _childInternalId = _ancestry.childInternalIdLookup[_childId];
return (
_childInternalId > 0 &&
!_ancestry.children[_childInternalId].approved &&
!_ancestry.children[_childInternalId].connected
);
}
/**
* @dev Add child TAO
* @param _taoId The TAO ID to be added to
* @param _childId The ID to be added to as child TAO
*/
function addChild(address _taoId, address _childId)
external
isTAO(_taoId)
isTAO(_childId)
onlyFactory returns (bool) {
require (!this.isChild(_taoId, _childId));
Ancestry storage _ancestry = ancestries[_taoId];
require (_ancestry.childInternalIdLookup[_childId] == 0);
_ancestry.childInternalId++;
_ancestry.childInternalIdLookup[_childId] = _ancestry.childInternalId;
Child storage _child = _ancestry.children[_ancestry.childInternalId];
_child.taoId = _childId;
// If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected
// Otherwise, child TAO needs parent TAO approval
address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId);
address _childAdvocate = _nameTAOPosition.getAdvocate(_childId);
emit AddChild(_taoId, _taoAdvocate, _childId, _childAdvocate, _child.approved, _child.connected);
if (_taoAdvocate == _childAdvocate) {
_approveChild(_taoId, _childId);
}
return true;
}
/**
* @dev Advocate of `_taoId` approves child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be approved
*/
function approveChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName
senderNameNotCompromised
onlyAdvocate(_taoId) {
require (isExist(_taoId) && isExist(_childId));
require (isNotApprovedChild(_taoId, _childId));
_approveChild(_taoId, _childId);
}
/**
* @dev Advocate of `_taoId` removes child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be removed
*/
function removeChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName
senderNameNotCompromised
onlyAdvocate(_taoId) {
require (this.isChild(_taoId, _childId));
Ancestry storage _ancestry = ancestries[_taoId];
_ancestry.totalChildren--;
Child storage _child = _ancestry.children[_ancestry.childInternalIdLookup[_childId]];
_child.connected = false;
_ancestry.childInternalIdLookup[_childId] = 0;
Ancestry storage _childAncestry = ancestries[_childId];
_childAncestry.parentId = address(0);
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId);
address _childAdvocate = _nameTAOPosition.getAdvocate(_childId);
emit RemoveChild(_taoId, _taoAdvocate, _childId, _childAdvocate, _nonce);
}
/**
* @dev Get list of child TAO IDs
* @param _taoId The TAO ID to be checked
* @param _from The starting index (start from 1)
* @param _to The ending index, (max is childInternalId)
* @return list of child TAO IDs
*/
function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[] memory) {
require (isExist(_taoId));
Ancestry storage _ancestry = ancestries[_taoId];
require (_from >= 1 && _to >= _from && _ancestry.childInternalId >= _to);
address[] memory _childIds = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_childIds[i.sub(_from)] = _ancestry.children[i].approved && _ancestry.children[i].connected ? _ancestry.children[i].taoId : address(0);
}
return _childIds;
}
/***** INTERNAL METHOD *****/
/**
* @dev Actually approving the child TAO
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be approved
*/
function _approveChild(address _taoId, address _childId) internal {
Ancestry storage _ancestry = ancestries[_taoId];
Ancestry storage _childAncestry = ancestries[_childId];
uint256 _childInternalId = _ancestry.childInternalIdLookup[_childId];
_ancestry.totalChildren++;
Child storage _child = _ancestry.children[_childInternalId];
_child.approved = true;
_child.connected = true;
_childAncestry.parentId = _taoId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId);
address _childAdvocate = _nameTAOPosition.getAdvocate(_childId);
emit ApproveChild(_taoId, _taoAdvocate, _childId, _childAdvocate, _nonce);
}
}
| Get list of child TAO IDs _taoId The TAO ID to be checked _from The starting index (start from 1) _to The ending index, (max is childInternalId) return list of child TAO IDs/ | function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[] memory) {
require (isExist(_taoId));
Ancestry storage _ancestry = ancestries[_taoId];
require (_from >= 1 && _to >= _from && _ancestry.childInternalId >= _to);
address[] memory _childIds = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_childIds[i.sub(_from)] = _ancestry.children[i].approved && _ancestry.children[i].connected ? _ancestry.children[i].taoId : address(0);
}
return _childIds;
}
| 12,869,875 |
pragma solidity ^0.4.21;
import "./LoanCdp.sol";
/**
* @title LoanIdentity
* @dev Contract used to determine unique identity of actors on protocol
* NOTE: Each actor must be verified using some identity
*/
contract LoanIdentity is LoanCdp {
mapping (address => uint[]) repayments;
mapping (address => uint[]) defaults;
/*** SETTERS ***/
/**
* @dev Adds repayment amount (in Wei) to repayments array of borrower
* @param _amt The size of repayment in the previous loan transaction being added
*/
function addToRepayments(address _address, uint _amt) internal {
repayments[_address].push(_amt);
}
/**
* @dev Adds default amount (in Wei) to defaults array of borrower
* @param _amt The size of repayment in the previous loan transaction being added
* NOTE: Not yet called
*/
function addToDefaults(address _address, uint _amt) internal {
defaults[_address].push(_amt);
}
/*** GETTERS ***/
/**
* @dev Given the address, return the repayment at a specific index
*/
function getRepayment(address _address, uint _index) external view returns (uint) {
return repayments[_address][_index];
}
/**
* @dev Given the address, return the default at a specific index
*/
function getDefault(address _address, uint _index) external view returns (uint) {
return defaults[_address][_index];
}
/**
* @dev Retrieves the number of repayments
*/
function getRepaymentsLength(address _address) external view returns (uint) {
return repayments[_address].length;
}
/**
* @dev Retrieves the number of defaults
*/
function getDefaultsLength(address _address) external view returns (uint) {
return defaults[_address].length;
}
}
| Given the address, return the default at a specific index/ | function getDefault(address _address, uint _index) external view returns (uint) {
return defaults[_address][_index];
}
| 15,793,903 |
./full_match/43114/0xC25148cB2a1CE39d121003f26422E724bD46782C/sources/contracts/StrategyRegistry.sol | Return a big ol list of strategy metadata | function viewAllEnabledStrategyMetadata()
external
view
returns (IStrategy.StrategyMetadata[] memory)
{
IStrategy.StrategyMetadata[]
memory result = new IStrategy.StrategyMetadata[](
totalTokenStratRows
);
uint256 enabledTotal = enabledStrategies.length();
uint256 resultI;
for (uint256 stratI; enabledTotal > stratI; stratI++) {
IStrategy strat = IStrategy(enabledStrategies.at(stratI));
IStrategy.StrategyMetadata[] memory meta = strat
.viewAllStrategyMetadata();
for (uint256 i; meta.length > i; i++) {
result[resultI + i] = meta[i];
}
resultI += meta.length;
}
return result;
}
| 4,635,147 |
./full_match/1/0xb9E82142F5B089A1818241047d893d83b5cfF9b1/sources/src/thirdparty/opensea/seadrop-upgradeable/src/ERC721SeaDropUpgradeable.sol | Update the public drop data for this nft contract on SeaDrop. Only the owner can use this function. seaDropImpl The allowed SeaDrop contract. publicDrop The public drop data./ Ensure the sender is only the owner or contract itself. Ensure the SeaDrop is allowed. Update the public drop data on SeaDrop. | function updatePublicDrop(address seaDropImpl, PublicDrop calldata publicDrop) external virtual override {
_onlyOwnerOrSelf();
_onlyAllowedSeaDrop(seaDropImpl);
ISeaDropUpgradeable(seaDropImpl).updatePublicDrop(publicDrop);
}
| 8,377,361 |
pragma solidity ^0.4.21;
// Seb: WARNING!!!
// explicit declaration of memory vs storage for complex types - arrays and structs
// state variable "array" is ambiguous and suspicious
import "./Owned.sol";
import "./Stash.sol";
import "./SGDz.sol";
contract PaymentAgent is Owned { // Regulator node (MAS) should be the owner
constructor() public {
owner = msg.sender;
agentState = AgentState.Normal;
/* default config */
maxQueueDepth = 100;
timeout = 10 * 1000000000; /* seconds */
proofTimeout = 20 * 1000000000; /* seconds */
}
address public zAddress;
function setZAddress(address _zAddress) public onlyOwner {
zAddress = _zAddress;
}
/* stashes */
bytes32[] public stashNames;
// JMR stashName => stash contract address
mapping (bytes32 => address) public stashRegistry;
/* salt tracking */
bytes16 public currentSalt; // used to retrieve shielded balance
bytes16 public nettingSalt; // used to cache result salt after LSM calculation
/* @pseudo-public
during LSM / confirming pmt: banks and cb will call this to set their current salt
@private for: [pledger]
during pledge / redeem: MAS-regulator / cb will invoke this function
*/
function setCurrentSalt(bytes16 _salt) public {
require(checkOwnedStash(acc2stash[msg.sender])); // non-owner will not update salt
if (acc2stash[msg.sender] != centralBank) {// when banks are setting salt, cb should not update its salt
require(msg.sender == owner || !isCentralBankNode()); // unless it invoked by MAS-regulator
} else {
require(isCentralBankNode()); // when cb are setting salt, banks should not update its salt
}
currentSalt = _salt;
}
/* @pseudo-public */
function setNettingSalt(bytes16 _salt) public {
require(checkOwnedStash(acc2stash[msg.sender])); // non-owner will not update salt
if (acc2stash[msg.sender] != centralBank) {// when banks are setting salt, cb should not update its salt
require(msg.sender == owner || !isCentralBankNode()); // unless it invoked by MAS-regulator
} else {
require(isCentralBankNode()); // when cb are setting salt, banks should not update its salt
}
nettingSalt = _salt;
}
// @pseudo-public, all the banks besides cb will not execute this action
function setCentralBankCurrentSalt(bytes16 _salt) public onlyCentralBank {
if (isCentralBankNode()) {
currentSalt = _salt;
}
}
function getCurrentSalt() public constant returns (bytes16) {
require(msg.sender == owner || checkOwnedStash(acc2stash[msg.sender]));
return currentSalt;
}
/* set up central bank */
bytes32 public centralBank;
function setCentralBank(bytes32 _stashName) public onlyOwner {
centralBank = _stashName;
}
modifier onlyCentralBank() { require(acc2stash[msg.sender] == centralBank); _; }
/* Suspend bank / stash */
mapping (bytes32 => bool) public suspended;
function suspendStash(bytes32 _stashName) public onlyOwner {
suspended[_stashName] = true;
}
function unSuspendStash(bytes32 _stashName) public onlyOwner {
suspended[_stashName] = false;
}
//modifier notSuspended(bytes32 _stashName) { require(suspended[_stashName] == false); _; }
event statusCode(int errorCode); // statusCode added to handle returns upon exceptions - Laks
// workaround to handle exception as require/throw do not return errors - need to refactor - Laks
modifier notSuspended(bytes32 _stashName) {
if ( suspended[_stashName] ) {
emit statusCode(100);
return;
}
_;
}
/* pledge | redeem */
struct Pledge {
bytes32 txRef;
bytes32 stashName;
int amount;
uint timestamp;
}
struct Redeem {
bytes32 txRef;
bytes32 stashName;
int amount;
uint timestamp;
}
bytes32[] public pledgeIdx;
mapping (bytes32 => Pledge) public pledges;
bytes32[] public redeemIdx;
mapping (bytes32 => Redeem) public redeems;
function getPledgeHistoryLength() public constant returns (uint) {
return pledgeIdx.length;
}
function getRedeemHistoryLength() public constant returns (uint) {
return redeemIdx.length;
}
/* payments */
// throw is deprecated, see https://solidity.readthedocs.io/en/develop/control-structures.html#error-handling-assert-require-revert-and-exceptions
//modifier isPositive(int _amount) { if (_amount <= 0 ) throw;_; }
//modifier isInvoled(bytes32 _sender, bytes32 _receiver) {
// if(!checkOwnedStash(_sender) && !checkOwnedStash(_receiver)) throw; _;
//}
modifier isPositive(int _amount) {
if (_amount <= 0 ) {
revert();
}
_;
}
modifier isInvoled(bytes32 _sender, bytes32 _receiver) {
if(!checkOwnedStash(_sender) && !checkOwnedStash(_receiver)) {
revert();
}
_;
}
// Pending: waiting for value transfer in z-contract, or waiting as receiver, or waiting
// for gridlock resolution procecss to finished
// Confirmed: value transfer in z-contract is completed
// Gridlocked: gridlocked payments
//UBIN-61 : added Canceled state, UBIN-63/64 - put on hold status- Laks
enum PmtState { Pending, Confirmed, Onhold, Cancelled }
struct Pmt {
bytes32 txRef;
bytes32 sender;
bytes32 receiver;
int amount; // > 0
PmtState state;
int express;
bool putInQueue;
uint timestamp; // added to include sorting in API layer - Laks
bytes16 salt;
}
uint public expressCount;
bytes32[] public pmtIdx; // @private (list of all-trans)
mapping (bytes32 => Pmt) public payments; // @private
function getSalt(bytes32 _txRef) public constant returns (bytes16) {
return payments[_txRef].salt;
}
function getOutgoingQueueDepth() public constant returns(uint) {
uint result = 0;
for (uint i = 0; i < gridlockQueue.length; ++i) {
if (payments[gridlockQueue[i]].sender == acc2stash[msg.sender]) {
result++;
}
}
return result;
}
//uint public inactivationTracker; //RH - omit cancel and hold from queue
bytes32[] public onholdPmts;
function getOnholdCount() public constant returns(uint) {
return onholdPmts.length;
}
function getOnholdPmtDetails(uint index) public constant returns( bytes32, bytes32, bytes32, int, PmtState, int, bool, uint){
bytes32 txRef = onholdPmts[index];
return (txRef, payments[txRef].sender, payments[txRef].receiver, payments[txRef].amount, payments[txRef].state, payments[txRef].express, payments[txRef].putInQueue, payments[txRef].timestamp);
}
function getPaymentAmount(bytes32 _txRef) public constant returns (int) {
require(checkOwnedStash(payments[_txRef].sender) || checkOwnedStash(payments[_txRef].receiver));
return payments[_txRef].amount;
}
bytes32[] public gridlockQueue; // @private
/* gridlock resolution facilities */
enum GridlockState { Cancelled, Inactive, Active, Onhold, Released }
struct GridlockedPmt {
GridlockState state;
bool receiverVote; // for receiver to indicate whether inactivation is acceptable
}
// key should be pmt sha3 hash. But currently txRef is used
// to globaqueue after checking queue.
uint public globalGridlockQueueDepth;
mapping (bytes32 => GridlockedPmt) public globalGridlockQueue;
uint public maxQueueDepth; // queue depth trigger
/* resolve sequence */
address[] public resolveSequence; // order of banks for round-robin in resolution steps
/* struct Participant { */
/* address ethKey; */
/* bool exists; */
/* } */
/* mapping(uint => Participant) resolveSequence; */
/* uint resolveSequenceLength; */
uint public current; // current resolving bank
mapping (address => bytes32) public acc2stash; // @pseudo-public
function registerStash(address _acc, bytes32 _stashName) public onlyOwner {
acc2stash[_acc] = _stashName;
}
modifier isStashOwner(bytes32 _stashName) {
require(msg.sender == owner || acc2stash[msg.sender] == _stashName);
_;
}
modifier onlySender(bytes32 _txRef) { require(acc2stash[tx.origin] == payments[_txRef].sender); _; }
modifier onlyTxParties(bytes32 _txRef) { require(acc2stash[tx.origin] == payments[_txRef].sender || acc2stash[tx.origin] == payments[_txRef].receiver); _; }
modifier onlyReceiver(bytes32 _txRef) { require(acc2stash[tx.origin] == payments[_txRef].receiver); _; }
// throw is deprecated, see https://solidity.readthedocs.io/en/develop/control-structures.html#error-handling-assert-require-revert-and-exceptions
//modifier isYourTurn() { if (resolveSequence[current] != msg.sender) throw; _; }
modifier isYourTurn() {
if (resolveSequence[current] != msg.sender) {
revert();
}
_;
}
/* state machine */
uint lineOpenTime; // time when the first participant is in line
uint public lastResolveTime; // time when the last participant did the resolve round
uint public timeout; // wait time for participants to line up
uint public proofTimeout;
uint resolveEndTime; // time when the current the resolve round finishes
function setTimeout(uint _timeout) public onlyOwner {
timeout = _timeout;
}
enum AgentState { Normal, Lineopen, Resolving, Settling }
AgentState public agentState;
// throw is deprecated, see https://solidity.readthedocs.io/en/develop/control-structures.html#error-handling-assert-require-revert-and-exceptions
//modifier atState(AgentState _state) { if (agentState != _state) throw; _; }
modifier atState(AgentState _state) {
if (agentState != _state) {
revert();
}
_;
}
event AgentStateChange(AgentState state);
function nextState() internal {
if (agentState == AgentState.Normal) globalGridlockQueueDepth = 0;
if (agentState == AgentState.Lineopen) { lineOpenTime = 0; lastResolveTime = now; }
if (agentState == AgentState.Resolving) { current = 0; resolveEndTime = now; }
if (agentState == AgentState.Settling) resolveSequence.length = 0;
agentState = AgentState((uint(agentState) + 1) % 4);
emit AgentStateChange(agentState);
}
// Note that this modifier is only added to resolution method, so if nobody
// has started to resolve then one can still join even if time's up.
mapping(address => uint) lastPingTime;
event Ping(uint delta, uint _timeout);
function ping() public {
lastPingTime[msg.sender] = now;
emit Ping(now - lastResolveTime, timeout);
}
modifier timedTransitions() {
if (agentState == AgentState.Lineopen) {
if (resolveSequence.length == stashNames.length || now >= lineOpenTime + timeout) {
nextState();
}
}
/* Non-lenient timeout kick-out rule */
int delta = getMyResolveSequenceId() - int(current);
uint resolveTimeout;
if (delta >= 0) {
resolveTimeout = timeout * uint(delta);
} else {
resolveTimeout = timeout * (uint(delta) + resolveSequence.length);
}
if (lastResolveTime == 0) lastResolveTime = now;
if (agentState == AgentState.Resolving &&
lastResolveTime + resolveTimeout <= lastPingTime[msg.sender] &&
lastPingTime[msg.sender] > lastPingTime[resolveSequence[current]]) {
for (uint i = current; i < resolveSequence.length-1; i++) {
resolveSequence[i] = resolveSequence[i+1];
}
delete resolveSequence[resolveSequence.length-1];
resolveSequence.length--;
}
_;
/* if (agentState == AgentState.Resolving && */
/* lastResolveTime + timeout <= now) { */
/* for (uint i = current; i < resolveSequence.length-1; i++) { */
/* resolveSequence[i] = resolveSequence[i+1]; */
/* } */
/* delete resolveSequence[resolveSequence.length-1]; */
/* resolveSequence.length--; */
/* } */
/* _; */
}
/* Sync Messaging */
mapping (bytes32 => bool) public done;
bytes32[] inactivatedPmtRefs;
bytes32[] doneStashes;
bytes32[] notDoneStashes;
bool committed;
function arrayEqual(bytes32[] a, bytes32[] b) public pure returns (bool) {
if (a.length != b.length) return false;
for (uint i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
modifier hasCommitted(bytes32[] _inactivatedPmtRefs,
bytes32[] _doneStashes,
bytes32[] _notDoneStashes)
{
if (checkOwnedStash(acc2stash[resolveSequence[current]]) &&
!(acc2stash[resolveSequence[current]] != centralBank && isCentralBankNode())) {
// if (!committed) throw; throw is deprecated, see https://solidity.readthedocs.io/en/develop/control-structures.html#error-handling-assert-require-revert-and-exceptions
if (!committed) revert();
else committed = false;
if (checkOwnedStash(acc2stash[resolveSequence[current]])) {
//if (!arrayEqual(_inactivatedPmtRefs, inactivatedPmtRefs)) throw; throw is deprecated
//if (!arrayEqual(_doneStashes, doneStashes)) throw; throw is deprecated
//if (!arrayEqual(_notDoneStashes, notDoneStashes)) throw; throw is deprecated
if (!arrayEqual(_inactivatedPmtRefs, inactivatedPmtRefs)) revert();
if (!arrayEqual(_doneStashes, doneStashes)) revert();
if (!arrayEqual(_notDoneStashes, notDoneStashes)) revert();
}
}
_;
}
/* @pseudo-public */
function createStash(bytes32 _stashName) public onlyOwner returns (bool){
address stash = new Stash(_stashName);
stashRegistry[_stashName] = stash;
stashNames.push(_stashName);
return true;
}
/* @depolyment:
privateFor = MAS and owner node */
function markStash(bytes32 _stashName) public onlyOwner {
Stash stash = Stash(stashRegistry[_stashName]);
stash.mark();
}
/* @live:
privateFor = MAS and participating node
In sender node, if the account has enough liquidity the payment would
be in status pending until the corresponding payment is made in the z-contract,
else the payment is copyed into the gridlock */
// timestamp is created onchain now - Zekun
event Payment(bytes32 txRef, bool gridlocked, bool confirmPmt);
function submitPmt(bytes32 _txRef, bytes32 _sender, bytes32 _receiver, int _amount,
int _express, bool _putInQueue, bytes16 _salt)
public
isPositive(_amount)
isInvoled(_sender, _receiver)
notSuspended(_sender)
notSuspended(_receiver)
{
//JMR
/* Stash sender = Stash(stashRegistry[_sender]); */
/* Stash receiver = Stash(stashRegistry[_receiver]); */
Pmt memory pmt = Pmt(_txRef,
_sender,
_receiver,
_amount,
PmtState.Pending,
_express,
_putInQueue,
now,
_salt);
pmtIdx.push(_txRef);
payments[_txRef] = pmt;
//update positions
Stash(stashRegistry[_sender]).dec_position(_amount);
Stash(stashRegistry[_receiver]).inc_position(_amount);
if (_putInQueue){
if (checkOwnedStash(_sender)) {
enqueue(_txRef, _express);
}
emit Payment(_txRef, true, false);
} else {
// enough balance (with LSM liquidity partition)
if (checkOwnedStash(_sender) && Stash(stashRegistry[_sender]).getBalance() >= _amount) {
if (getOutgoingQueueDepth() < 1 ||
(_express == 1 && expressCount < 1) ) { //no queue //express and no express queue
emit Payment(_txRef, false, false);
} else { //queue but enough balance
enqueue(_txRef, _express);// put in end of queue
emit Payment(_txRef, true, false);
}
} else if (checkOwnedStash(_sender)) {// if not enough balance all goes to queue
enqueue(_txRef, _express);
emit Payment(_txRef, true, false);
}
}
}
/* pseudo-public */
function releasePmt(bytes32 _txRef) public atState(AgentState.Normal) {
/* require(pmtProved(_txRef)); */
require(globalGridlockQueue[_txRef].state == GridlockState.Active ||
globalGridlockQueue[_txRef].state == GridlockState.Inactive);
delete globalGridlockQueue[_txRef];
globalGridlockQueueDepth--;
globalGridlockQueue[_txRef].state = GridlockState.Released;
removeByValue('gridlockQueue', _txRef);
}
/* @pseudo-public */
// need to orchestrate the adding to the global gridlockqueue
function addToGlobalQueue(bytes32 _txRef) public atState(AgentState.Normal) {
globalGridlockQueueDepth++;
globalGridlockQueue[_txRef].state = GridlockState.Active;
globalGridlockQueue[_txRef].receiverVote = true;
if (globalGridlockQueueDepth >= maxQueueDepth) nextState();
if (isReceiver(_txRef)) enqueue(_txRef, payments[_txRef].express);
}
//UBIN-61 ***************************
//remove items from global queue if not in LSM process
/* function removeFromGlobalQueue(bytes32 txRef) atState(AgentState.Normal) { */
/* //delete item from the dictionary */
/* /\* delete globalGridlockQueue[txRef]; *\/ */
/* globalGridlockQueue[txRef].exists = false; */
/* //decrement the global queue */
/* globalGridlockQueueDepth--; */
/* if (isReceiver(txRef)) { */
/* //Delete the payment from the receiver's gridlockqueue */
/* removeByValue(gridlockQueue, txRef); */
/* } */
/* } */
function isReceiver(bytes32 txRef) private view returns (bool) {
for (uint i = 0; i < pmtIdx.length; i++) {
//find matching payment index.
if (pmtIdx[i] == txRef) {
// N.B. only MAS will control both sender and receiver stash
if (checkOwnedStash(payments[pmtIdx[i]].receiver) &&
!checkOwnedStash(payments[pmtIdx[i]].sender)) {
return true;
}
}
}
return false;
}
event Time(uint remainingTime);
/* @pseudo-public
Determine the resolve sequence, and broadcast gridlocked payments to
receivers */
function lineUp()
public
atState(AgentState.Lineopen)
//isStashOwner(_stashName)
{
if (lineOpenTime == 0) { lineOpenTime = now; }
resolveSequence.push(msg.sender);
/* acc2stash[msg.sender] = _stashName; */
done[acc2stash[msg.sender]] = false;
emit Time(lineOpenTime + timeout - now);
if (resolveSequence.length == stashNames.length) nextState();
}
function isParticipating(bytes32 _stashName) internal view returns (bool) {
for (uint i = 0; i < resolveSequence.length; i++) {
if (acc2stash[resolveSequence[i]] == _stashName) return true;
}
return false;
}
/* for testing */
event Hash(bytes32 hash, bytes32 a);
function doHash(uint256 _a) public {
// bytes32 result = keccak256(_a); Warning: This function only accepts a single "bytes" argument. Please use "abi.encodePacked(...)" or a similar function to encode the data.
bytes32 result = keccak256(abi.encodePacked(_a));
emit Hash(result, bytes32(_a));
}
function doHashBytes(bytes32 _a) public {
//bytes32 result = keccak256(_a); Warning: This function only accepts a single "bytes" argument. Please use "abi.encodePacked(...)" or a similar function to encode the data.
bytes32 result = keccak256(abi.encodePacked(_a));
emit Hash(result, _a);
}
function doHashBytes2(bytes32 _a, bytes32 _b) public {
//bytes32 result = keccak256(_a, _b); Warning: This function only accepts a single "bytes" argument. Please use "abi.encodePacked(...)" or a similar function to encode the data.
bytes32 result = keccak256(abi.encodePacked(_a, _b));
emit Hash(result, _a);
}
event Answer(bool a);
event Num(uint n);
function verify() public {
bytes32 key = 'R1231';
emit Answer(payments[key].txRef == bytes32(''));
emit Num(uint(-1));
}
event Array(bytes32[] a);
bytes32[] array;
function emitArray(bytes32 a, bytes32 b) public {
array.push(a);
array.push(b);
emit Array(array);
}
function bytesArrayInput(bytes32[] _input) public {
emit Array(_input);
}
/* function getStashNames() { */
/* Array(stashNames); */
/* } */
function getStashNames() public constant returns (bytes32[]) {
return stashNames;
}
/* @pseudo-public
THIS METHOD WILL BREAK THE PSEUDO-PUBLIC STATES.
However you should still make a pseudo-public call as we want to update PaymentAgent's
state on all the nodes.
You'll need to call syncPseudoPublicStates after calling this method to sync up
the pseudo-public states. */
event Sync(bytes32[] inactivatedPmtRefs, bytes32[] doneStashes, bytes32[] notDoneStashes);
function doResolveRound()
public
timedTransitions
atState(AgentState.Resolving)
isYourTurn
returns (bool _didResolution)
{
lastResolveTime = now;
bytes32 currentStash = acc2stash[resolveSequence[current]];
if (!checkOwnedStash(currentStash)) { return false; }
if (currentStash != centralBank && isCentralBankNode()) { return false; }
for (uint i = 0; i < gridlockQueue.length; i++) {
Pmt memory inflow = payments[gridlockQueue[i]]; // "inflow" read-only
GridlockedPmt storage g_inflow = globalGridlockQueue[inflow.txRef]; /* to be changed */
// Seb: g_flow points to an globalGridlockQueue array element, and could be updated
/* deactivate inflows from non-participant*/
if (!isParticipating(inflow.sender) && g_inflow.state == GridlockState.Active) {
g_inflow.state = GridlockState.Inactive;
Stash(stashRegistry[inflow.sender]).inc_position(inflow.amount);
Stash(stashRegistry[inflow.receiver]).dec_position(inflow.amount);
}
}
/* Bilateral EAF2 */
inactivatedPmtRefs.length = 0;
for (uint j = gridlockQueue.length-1; j >= 0; j--) { // reverse chronological order
if (Stash(stashRegistry[currentStash]).getPosition() >= 0) break; // LSM liquidity partition
Pmt memory pmt = payments[gridlockQueue[j]]; // local variable "pmt" read-only
GridlockedPmt storage g_pmt = globalGridlockQueue[pmt.txRef]; /* to be changed */
// Seb: g_pmt points to an globalGridlockQueue array element, and could be updated
/* vote on your outflows */
if (pmt.sender == currentStash && g_pmt.state == GridlockState.Active) {
g_pmt.state = GridlockState.Inactive;
inactivatedPmtRefs.push(pmt.txRef);
Stash(stashRegistry[pmt.sender]).inc_position(pmt.amount);
Stash(stashRegistry[pmt.receiver]).dec_position(pmt.amount);
done[pmt.receiver] = false;
}
}
done[currentStash] = true;
/* emit sync info */
doneStashes.length = 0;
notDoneStashes.length = 0;
for (uint k = 0; k < resolveSequence.length; k++) {
bytes32 stashName = acc2stash[resolveSequence[k]];
if (done[stashName]) doneStashes.push(stashName);
else notDoneStashes.push(stashName);
}
emit Sync(inactivatedPmtRefs, doneStashes, notDoneStashes);
committed = true;
return true;
}
function allDone() internal view returns (bool) {
bool alldone = true;
for (uint i = 0; i < resolveSequence.length; i++) {
if (!done[acc2stash[resolveSequence[i]]]) {
alldone = false;
break;
}
}
return alldone;
}
function receiverInactivate(bytes32 _txRef) private returns (bool _isReceiver) {
for (uint i = 0; i < gridlockQueue.length; i++) {
Pmt memory pmt = payments[gridlockQueue[i]]; // pmt read-only
if (pmt.txRef == _txRef) {
if (!checkOwnedStash(pmt.receiver)) return false;
Stash(stashRegistry[pmt.sender]).inc_position(pmt.amount);
Stash(stashRegistry[pmt.receiver]).dec_position(pmt.amount);
return true;
}
}
}
event AllDone(bool allDone, uint current);
/* @pseudo-public */
function syncPseudoPublicStates(bytes32[] _inactivatedPmtRefs,
bytes32[] _doneStashes,
bytes32[] _notDoneStashes)
public
atState(AgentState.Resolving)
isYourTurn
hasCommitted(_inactivatedPmtRefs, _doneStashes, _notDoneStashes)
{
/* syncing global queue */
globalGridlockQueueDepth += _inactivatedPmtRefs.length;
for (uint i = 0; i < _inactivatedPmtRefs.length; i++) {
globalGridlockQueue[_inactivatedPmtRefs[i]].state = GridlockState.Inactive;
receiverInactivate(_inactivatedPmtRefs[i]);
}
/* syncing done mapping */
for (uint j = 0; j < _doneStashes.length; j++) {
done[_doneStashes[j]] = true;
}
for (uint k = 0; k < _notDoneStashes.length; k++) {
done[_notDoneStashes[k]] = false;
}
/* if everyone is done, enter netting phase, else pass on to the next participant */
bool alldone = allDone();
current++;
if (current == resolveSequence.length) current = 0;
emit AllDone(alldone, current);
if (alldone == true) nextState();
}
/* @pseudo-public */
//update private balance , update zcontract first then local balance, used at the end of the
// LSM process only.
event Deadlock();
function settle() public atState(AgentState.Settling) {
/* netting by doing net balance movement */
for (uint i = 0; i < stashNames.length; i++) {
Stash stash = Stash(stashRegistry[stashNames[i]]);
int net_diff = stash.getPosition() - stash.getBalance();
if (net_diff > 0) {
stash.credit(net_diff);
} else if (net_diff < 0) {
if (checkOwnedStash(stashNames[i])) {
stash.safe_debit(-net_diff);
} else {
stash.debit(-net_diff);
}
}
}
/* 1. confirm and dequeue active gridlocked payments
2. reactivate inactive gridlocked payments and update position accordingly */
uint beforeSettleGridlockCount = gridlockQueue.length;
uint numGridlockedPmts = 0;
for (uint j = 0; j < gridlockQueue.length; j++) {
/* require(pmtProved(gridlockQueue[j])); */
// Seb: both pmt and g_pmt print to array elements and could be updated
Pmt storage pmt = payments[gridlockQueue[j]];
GridlockedPmt storage g_pmt = globalGridlockQueue[pmt.txRef]; /* to be changed */
if (g_pmt.state == GridlockState.Active) {
g_pmt.state = GridlockState.Released; // Changed
pmt.state = PmtState.Confirmed;
} else if (g_pmt.state == GridlockState.Inactive) { // reactivate inactive pmts
g_pmt.state = GridlockState.Active;
Stash(stashRegistry[pmt.sender]).dec_position(pmt.amount);
Stash(stashRegistry[pmt.receiver]).inc_position(pmt.amount);
gridlockQueue[numGridlockedPmts] = pmt.txRef;
numGridlockedPmts++;
} else if (g_pmt.state == GridlockState.Onhold) {
gridlockQueue[numGridlockedPmts] = pmt.txRef;
numGridlockedPmts++;
}
}
if (beforeSettleGridlockCount == numGridlockedPmts) {
emit Deadlock();
/* maxQueueDepth += 5; // prevent recursive gridlock */
} else if (isNettingParticipant()) {
currentSalt = nettingSalt;
}
gridlockQueue.length = numGridlockedPmts;
nextState();
}
// current resolve round leader can stop the LSM if timeout
function moveOn() public atState(AgentState.Settling) isYourTurn {
require(now >= resolveEndTime + proofTimeout);
nextState();
}
/* function pmtProved(bytes32 _txRef) external constant returns (bool) { */
/* return SGDz(zAddress).pmtProcessed(_txRef); */
/* } */
/* function pmtProved(bytes32 _txRef) external constant returns (bool) { */
/* return SGDz(zAddress).paymentIsValidated(_txRef); */
/* } */
function pmtProved(bytes32 _txRef) external constant returns (bool) {
return SGDz(zAddress).proofCompleted(_txRef);
}
/* @private for: [sender, receiver, (MAS)] */
function confirmPmt(bytes32 _txRef) public atState(AgentState.Normal) onlyReceiver(_txRef) {
//comment out to get it to work
/* require(pmtProved(_txRef)); */
transfer(payments[_txRef].sender,
payments[_txRef].receiver,
payments[_txRef].amount);
payments[_txRef].state = PmtState.Confirmed;
currentSalt = payments[_txRef].salt;
}
// update balance
function transfer(bytes32 _sender, bytes32 _receiver, int _amount) private {
Stash sender = Stash(stashRegistry[_sender]);
Stash receiver = Stash(stashRegistry[_receiver]);
if (checkOwnedStash(_sender)) {
sender.safe_debit(_amount);
} else {
sender.debit(_amount);
}
receiver.credit(_amount);
}
// UBIN-61 ///////////////////////////////////////////////////
// @pseudo-public == privateFor: [everyone]
// ----------------------------------------------------------
// UBIN-61 [Quorum] Cancel unsettled outgoing payment instruction - Laks
// ----------------------------------------------------------
function cancelPmtFromGlobalQueue(bytes32 _txRef)
public
atState(AgentState.Normal)
//onlySender(_txRef)
{
require(globalGridlockQueue[_txRef].state != GridlockState.Cancelled);
if (globalGridlockQueue[_txRef].state != GridlockState.Onhold){
globalGridlockQueueDepth--;
delete globalGridlockQueue[_txRef];
}
globalGridlockQueue[_txRef].state = GridlockState.Cancelled;
}
//anything other than agent state Normal will get rejected
// @privateFor: [receiver, (optional MAS)]
// call this after cancelPmtFromGlobalQueue
function cancelPmt(bytes32 _txRef)
public
atState(AgentState.Normal)
onlySender(_txRef)
{
if (suspended[payments[_txRef].sender]){
emit statusCode(600);
return;
}
require(( payments[_txRef].state == PmtState.Pending ) ||
( payments[_txRef].state == PmtState.Onhold ));
require(globalGridlockQueue[_txRef].state != GridlockState.Cancelled);
bool changePosition = false;
if (payments[_txRef].state == PmtState.Pending) changePosition = true;
if (payments[_txRef].state == PmtState.Onhold) removeByValue('onholdPmts', _txRef);
payments[_txRef].state = PmtState.Cancelled;
//if high priority, decrement express count
if (payments[_txRef].express == 1) {
expressCount--;
}
//remove item from gridlock array
removeByValue('gridlockQueue', _txRef);
// instead of doing this, we have compress the cancelled item in settle()
if (changePosition) updatePosition(_txRef, true);
// if (success) Status(_txRef,true);
//inactivationTracker++;
emit Status(_txRef, true);
}
// ---------------------------------------------------------------------------
// UBIN-62 - Put unsettled outgoing payment instruction on hold - Laks
// @pseudo-public
// ---------------------------------------------------------------------------
function holdPmtFromGlobalQueue(bytes32 _txRef)
public
atState(AgentState.Normal)
//onlySender(_txRef)
{
require((globalGridlockQueue[_txRef].state != GridlockState.Onhold) && (globalGridlockQueue[_txRef].state != GridlockState.Cancelled));
GridlockedPmt storage g_pmt = globalGridlockQueue[_txRef]; // g_pmt points to array element and will be updated
g_pmt.state = GridlockState.Onhold;
globalGridlockQueueDepth--;
}
// ---------------------------------------------------------------------------
// UBIN-62 - Put unsettled outgoing payment instruction on hold - Laks
// @privateFor: [receiver, (optional MAS)]
// ---------------------------------------------------------------------------
event Status(bytes32 txRef, bool holdStatus);
function holdPmt (bytes32 _txRef)
public
atState(AgentState.Normal)
onlySender(_txRef)
{
if (suspended[payments[_txRef].sender]){
emit statusCode(700);
return;
}
require(payments[_txRef].state == PmtState.Pending);
require(globalGridlockQueue[_txRef].state != GridlockState.Onhold);
payments[_txRef].state = PmtState.Onhold;
onholdPmts.push(_txRef);
updatePosition(_txRef, true);
removeByValue('gridlockQueue', _txRef);
if (payments[_txRef].state == PmtState.Onhold) {
//inactivationTracker++;
emit Status(_txRef, true);
}
else emit Status(_txRef, false);
// Debug message - acc2stash[msg.sender] is empty leading to onlySender to fail - Laks
}
// ---------------------------------------------------------------------------
// UBIN-63 - Reactivate unsettled payment instruction that is on hold - Laks
// @privateFor: [receiver, (optional MAS)]
// ---------------------------------------------------------------------------
function unholdPmt (bytes32 _txRef)
public
atState(AgentState.Normal)
onlySender(_txRef)
{
if (suspended[payments[_txRef].sender]){
emit statusCode(800);
return;
}
require(payments[_txRef].state == PmtState.Onhold);
require(globalGridlockQueue[_txRef].state == GridlockState.Onhold);
payments[_txRef].state = PmtState.Pending;
removeByValue('onholdPmts', _txRef);
enqueue(_txRef, payments[_txRef].express);
updatePosition(_txRef, false);
if (payments[_txRef].state == PmtState.Pending) {
//inactivationTracker--;
emit Status(_txRef, false);
}
else emit Status(_txRef, true);
}
// ---------------------------------------------------------------------------
// UBIN-63 - Reactivate unsettled payment instruction that is on hold - Laks
// @pseudo-public
// called after unholdPmt
// ---------------------------------------------------------------------------
function unholdPmtFromGlobalQueue(bytes32 _txRef)
public
atState(AgentState.Normal)
//onlySender(_txRef)
{
//remove item from globalGridlockQueue
require(globalGridlockQueue[_txRef].state == GridlockState.Onhold);
GridlockedPmt storage g_pmt = globalGridlockQueue[_txRef]; // g_pmt points to array element and will be updated
g_pmt.state = GridlockState.Active;
globalGridlockQueueDepth++;
}
function updatePosition(bytes32 _txRef, bool reverse) internal {
Stash senderStash = Stash(stashRegistry[payments[_txRef].sender]);
Stash receiverStash = Stash(stashRegistry[payments[_txRef].receiver]);
if (reverse) {
//increase sender's position, queued item removed
senderStash.inc_position(payments[_txRef].amount);
receiverStash.dec_position(payments[_txRef].amount);
} else {
//decrease sender's position, queue item added
senderStash.dec_position(payments[_txRef].amount);
receiverStash.inc_position(payments[_txRef].amount);
}
}
///////////////////////////////////////////////////////////////////
/* @live:
privateFor == MAS and owner node
This method is set to onlyonwer as pledge include off-chain process
*/
function pledge(bytes32 _txRef, bytes32 _stashName, int _amount)
public
// onlyCentralBank
notSuspended(_stashName)
{
if (_stashName != centralBank || isCentralBankNode()) {
Stash stash = Stash(stashRegistry[_stashName]);
stash.credit(_amount);
stash.inc_position(_amount);
pledgeIdx.push(_txRef);
pledges[_txRef].txRef = _txRef;
pledges[_txRef].stashName = _stashName;
pledges[_txRef].amount = _amount;
pledges[_txRef].timestamp = now;
}
}
/* @live:
privateFor = MAS and owner node */
function redeem(bytes32 _txRef, bytes32 _stashName, int _amount)
public
//onlyCentralBank
notSuspended(_stashName)
{
if (_stashName != centralBank || isCentralBankNode()) {
Stash stash = Stash(stashRegistry[_stashName]);
stash.safe_debit(_amount);
stash.dec_position(_amount);
redeemIdx.push(_txRef);
redeems[_txRef].txRef = _txRef;
redeems[_txRef].stashName = _stashName;
redeems[_txRef].amount = _amount;
redeems[_txRef].timestamp = now;
}
}
/* UBIN-153 insert into queue based on priority level */
function enqueue(bytes32 _txRef, int _express) internal {
if (_express == 0) {
gridlockQueue.push(_txRef);
} else if (_express == 1){
// todo: can potentially use the updateGridlockQueue func
if (gridlockQueue.length == expressCount) { // all express payment
gridlockQueue.push(_txRef);
} else {
gridlockQueue.push(gridlockQueue[gridlockQueue.length-1]);
for (uint i = gridlockQueue.length - 1; i > expressCount; i--) {
gridlockQueue[i] = gridlockQueue[i-1];
}
gridlockQueue[expressCount] = _txRef;
}
expressCount++;
}
}
/* @live:
for stashes not owned by you this returns the net bilateral position */
function getBalance(bytes32 _stashName) public isStashOwner(_stashName) constant returns (int) {
Stash stash = Stash(stashRegistry[_stashName]);
return stash.getBalance();
}
function getPosition(bytes32 _stashName) public isStashOwner(_stashName) constant returns (int) {
Stash stash = Stash(stashRegistry[_stashName]);
return stash.getPosition();
}
function getLineLength() public constant returns (uint) {
return resolveSequence.length;
}
function getHistoryLength() public constant returns (uint) {
return pmtIdx.length;
}
function getGridlockQueueDepth() public constant returns (uint) {
return gridlockQueue.length;
}
function getGlobalGridlockQueueDepth() public constant returns (uint) {
return globalGridlockQueueDepth;
}
function getIsPaymentActive(bytes32 _txRef) external constant returns(bool) {
GridlockedPmt memory g_pmt = globalGridlockQueue[_txRef]; /* to be changed */
// g_pmt points to array element and read-only
if(g_pmt.state == GridlockState.Active){
return true;
} else {
return false;
}
}
//given a bank, check if it is the owner
function checkOwnedStash(bytes32 _stashName) public constant returns (bool) {
if (msg.sender == owner) return true; // MAS does not need to mark its own stash
Stash stash = Stash(stashRegistry[_stashName]);
return stash.isControlled();
}
function isNettingParticipant() public constant returns (bool) {
bytes32 myStashName = getOwnedStash();
for (uint i = 0; i < resolveSequence.length; ++i) {
if (myStashName == acc2stash[resolveSequence[i]]) return true;
}
return false;
}
function getOwnedStash() public constant returns (bytes32) {
if (isCentralBankNode()) return centralBank;
for (uint i = 0; i < stashNames.length; i++) {
Stash stash = Stash(stashRegistry[stashNames[i]]);
if (stash.isControlled()) {
return stashNames[i];
}
}
}
// Central bank controls all the stashes
function isCentralBankNode() public constant returns (bool) {
for (uint i = 0; i < stashNames.length; i++) {
Stash stash = Stash(stashRegistry[stashNames[i]]);
if (!stash.isControlled()) {
return false;
}
}
return true;
}
function getThreshold() public constant returns (uint) {
return maxQueueDepth;
}
function setThreshold(uint _threshold) public onlyOwner {
maxQueueDepth = _threshold;
}
function getAgentState() public constant returns (uint) {
if(agentState == AgentState.Normal){
return 0;
} else if (agentState == AgentState.Lineopen){
return 1;
} else if (agentState == AgentState.Resolving){
return 2;
} else if (agentState == AgentState.Settling){
return 3;
}
}
function getResolveSequence() public constant returns (address[]) {
return resolveSequence;
}
function getResolveSequenceLength() public constant returns (uint) {
return resolveSequence.length;
}
function getCurrentStash() public constant returns (bytes32) {
return acc2stash[resolveSequence[current]];
}
function getMyResolveSequenceId() public constant returns (int) {
for (uint i = 0; i < resolveSequence.length; i++) {
if (resolveSequence[i] == tx.origin) return int(i);
}
return -1;
}
function getActiveGridlockCount() public constant returns (uint) {
uint result = 0;
for (uint i = 0; i < gridlockQueue.length-1; i++) {
// pmt and g_pmt point to array elements and read-only
Pmt storage pmt = payments[gridlockQueue[i]];
GridlockedPmt storage g_pmt = globalGridlockQueue[pmt.txRef]; /* to be changed */
if (g_pmt.state == GridlockState.Active) result++;
}
return result;
}
function IndexOf(bytes32[] values, bytes32 value) public pure returns(uint) {
uint i ;
bool found = true;
for(i = 0; i< values.length; i++){
if ( values[i] == value ){
found=true;
break;
}
}
if (found)
return i;
else
return 99999999;
}
// ------------------------------
// Implementation of UBIN-60 - Laks
// ------------------------------
function updatePriority(bytes32 _txRef, int _express) public {
// var (i,found) = ArrayIndexOf(pmtIdx,_txRef); Warning: Use of the "var" keyword is deprecated.
uint i;
bool found;
(i,found) = ArrayIndexOf(pmtIdx,_txRef);
if (!found) {
emit statusCode(300);
return;
}
if ( suspended[payments[_txRef].sender ]){
emit statusCode(400);
return;
}
require(payments[_txRef].express != _express); // no update when the priority level is the same
if (payments[_txRef].express == 0) {
expressCount++;
} else if (payments[_txRef].express == 1){
expressCount--;
}
payments[_txRef].express = _express;
updateGridlockQueue(_txRef);
}
// -----------------------------------------------------
// TO DO - To be refactored into a common untils - Laks
// -----------------------------------------------------
function ArrayIndexOf(bytes32[] values, bytes32 value) internal pure returns (uint,bool) {
bool found = false;
uint i;
for(i=0; i< values.length; i++){
if ( values[i] == value ){
found=true;
break;
}
}
if (found)
return (i,found);
else
return (0,found);
}
// ------------------------------------
// Keep the gridlock queue sorted by 1. priority level 2. timestamp
// Might need a more generic quick sort function in future
// Assumes that the gridlockqueue is already sorted before the current txn
// ------------------------------------
function updateGridlockQueue(bytes32 _txRef) public {
uint tstamp = payments[_txRef].timestamp;
uint i;
bytes32 curTxRef;
uint curTstamp;
int curExpress;
//var (index, found) = ArrayIndexOf(gridlockQueue, _txRef); Warning: Use of the "var" keyword is deprecated.
uint index;
bool found;
(index, found) = ArrayIndexOf(gridlockQueue, _txRef);
uint j = index;
if (payments[_txRef].express == 1){
// shift the txn to the left
if (index == 0) return;
for (i=index-1; int(i)>=0 ;i--){ // rather painful discovery that uint i>=0 doesn't work :( - Jay
curTxRef = gridlockQueue[i];
curTstamp = payments[curTxRef].timestamp;
curExpress = payments[curTxRef].express;
if (curExpress == 0 || tstamp < curTstamp){
gridlockQueue[i] = _txRef;
gridlockQueue[j] = curTxRef;
j--;
}
}
} else {
// shift the txn to the right
if (index == gridlockQueue.length-1) return;
for (i=index+1;i<=gridlockQueue.length-1;i++){
curTxRef = gridlockQueue[i];
curTstamp = payments[curTxRef].timestamp;
curExpress = payments[curTxRef].express;
if (curExpress == 1 || tstamp > curTstamp){
gridlockQueue[i] = _txRef;
gridlockQueue[j] = curTxRef;
j++;
}
}
}
}
// ------------------------------------
// ------------------------------------
// Removes the given value in an array
// Refactored to use ArrayIndexOf - Laks
// ------------------------------------
function removeByValue(bytes32 arrayName, bytes32 value) internal returns (bool) {
//bytes32[] array; Warning: This declaration shadows an existing declaration.
// Seb: DANGER ZONE - ambiguous !!!
// "array" is declared as state variable above and this function seems to be modifying the same state variable at the end.
//TODO use a mapping?
if (arrayName == 'onholdPmts'){
array = onholdPmts;
} else if (arrayName == 'gridlockQueue'){
array = gridlockQueue;
if (payments[value].express == 1) expressCount--;
} else {
return false;
}
//var (index, found) = ArrayIndexOf(array,value); Warning: Use of the "var" keyword is deprecated.
uint index;
bool found;
(index, found) = ArrayIndexOf(array,value);
if (found) {
for (uint i=index;i<array.length-1;i++){
array[i] = array[i+1];
}
delete array[array.length-1];
array.length--;
return true;
}
return false;
}
//util functions- added for debug and testing///
//not to be used by app. //////////////////////
//Only use from debug and testing scripts///////
function clearQueue() public {
for (uint i = 0; i < gridlockQueue.length; i++){
delete globalGridlockQueue[gridlockQueue[i]];
}
globalGridlockQueueDepth = 0;
gridlockQueue.length = 0;
onholdPmts.length = 0;
expressCount = 0;
//inactivationTracker = 0;
}
function wipeout() public {
clearQueue();
for (uint i = 0; i < pmtIdx.length; i++){
delete payments[pmtIdx[i]];
}
pmtIdx.length = 0;
agentState = AgentState.Normal;
stashNames.length = 0;
resolveSequence.length = 0;
current = 0;
}
}
| increase sender's position, queued item removeddecrease sender's position, queue item added | function unholdPmtFromGlobalQueue(bytes32 _txRef)
public
atState(AgentState.Normal)
}
if (reverse) {
senderStash.inc_position(payments[_txRef].amount);
receiverStash.dec_position(payments[_txRef].amount);
senderStash.dec_position(payments[_txRef].amount);
receiverStash.inc_position(payments[_txRef].amount);
}
| 14,074,680 |
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./interface/IxAsset.sol";
import "./interface/IxTokenManager.sol";
/**
* @title RevenueController
* @author xToken
*
* RevenueController is the management fees charged on xAsset funds. The RevenueController contract
* claims fees from xAssets, exchanges fee tokens for XTK via 1inch (off-chain api data will need to
* be passed to permissioned function `claimAndSwap`), and then transfers XTK to Mgmt module
*/
contract RevenueController is Initializable, OwnableUpgradeable {
using SafeERC20 for IERC20;
/* ============ State Variables ============ */
// Index of xAsset
uint256 public nextFundIndex;
// Address of xtk token
address public constant xtk = 0x7F3EDcdD180Dbe4819Bd98FeE8929b5cEdB3AdEB;
// Address of Mgmt module
address public managementStakingModule;
// Address of OneInchExchange contract
address public oneInchExchange;
// Address to indicate ETH
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
//
address public xtokenManager;
// xAsset to index
mapping(address => uint256) private _fundToIndex;
// xAsset to array of asset address that charged as fee
mapping(address => address[]) private _fundAssets;
// Index to xAsset
mapping(uint256 => address) private _indexToFund;
/* ============ Events ============ */
event FeesClaimed(address indexed fund, address indexed revenueToken, uint256 revenueTokenAmount);
event RevenueAccrued(address indexed fund, uint256 xtkAccrued, uint256 timestamp);
event FundAdded(address indexed fund, uint256 indexed fundIndex);
/* ============ Modifiers ============ */
modifier onlyOwnerOrManager {
require(
msg.sender == owner() || IxTokenManager(xtokenManager).isManager(msg.sender, address(this)),
"Non-admin caller"
);
_;
}
/* ============ Functions ============ */
function initialize(
address _managementStakingModule,
address _oneInchExchange,
address _xtokenManager
) external initializer {
__Ownable_init();
nextFundIndex = 1;
managementStakingModule = _managementStakingModule;
oneInchExchange = _oneInchExchange;
xtokenManager = _xtokenManager;
}
/**
* Withdraw fees from xAsset contract, and swap fee assets into xtk token and send to Mgmt
*
* @param _fundIndex Index of xAsset
* @param _oneInchData 1inch low-level calldata(generated off-chain)
*/
function claimAndSwap(uint256 _fundIndex, bytes[] memory _oneInchData) external onlyOwnerOrManager {
require(_fundIndex > 0 && _fundIndex < nextFundIndex, "Invalid fund index");
address fund = _indexToFund[_fundIndex];
address[] memory fundAssets = _fundAssets[fund];
require(_oneInchData.length == fundAssets.length, "Params mismatch");
IxAsset(fund).withdrawFees();
for (uint256 i = 0; i < fundAssets.length; i++) {
uint256 revenueTokenBalance = getRevenueTokenBalance(fundAssets[i]);
if (revenueTokenBalance > 0) {
emit FeesClaimed(fund, fundAssets[i], revenueTokenBalance);
if (_oneInchData[i].length > 0) {
swapAssetToXtk(fundAssets[i], _oneInchData[i]);
}
}
}
uint256 xtkBalance = IERC20(xtk).balanceOf(address(this));
IERC20(xtk).safeTransfer(managementStakingModule, xtkBalance);
emit RevenueAccrued(fund, xtkBalance, block.timestamp);
}
function swapOnceClaimed(
uint256 _fundIndex,
uint256 _fundAssetIndex,
bytes memory _oneInchData
) external onlyOwnerOrManager {
require(_fundIndex > 0 && _fundIndex < nextFundIndex, "Invalid fund index");
address fund = _indexToFund[_fundIndex];
address[] memory fundAssets = _fundAssets[fund];
require(_fundAssetIndex < fundAssets.length, "Invalid fund asset index");
swapAssetToXtk(fundAssets[_fundAssetIndex], _oneInchData);
uint256 xtkBalance = IERC20(xtk).balanceOf(address(this));
IERC20(xtk).safeTransfer(managementStakingModule, xtkBalance);
emit RevenueAccrued(fund, xtkBalance, block.timestamp);
}
function swapAssetToXtk(address _fundAsset, bytes memory _oneInchData) private {
uint256 revenueTokenBalance = getRevenueTokenBalance(_fundAsset);
bool success;
if (_fundAsset == ETH_ADDRESS) {
// execute 1inch swap of ETH for XTK
(success, ) = oneInchExchange.call{ value: revenueTokenBalance }(_oneInchData);
} else {
// execute 1inch swap of token for XTK
(success, ) = oneInchExchange.call(_oneInchData);
}
require(success, "Low-level call with value failed");
}
/**
* Governance function that adds xAssets
* @param _fund Address of xAsset
* @param _assets Assets charged as fee in xAsset
*/
function addFund(address _fund, address[] memory _assets) external onlyOwner {
require(_fundToIndex[_fund] == 0, "Already added");
require(_assets.length > 0, "Empty fund assets");
_indexToFund[nextFundIndex] = _fund;
_fundToIndex[_fund] = nextFundIndex++;
_fundAssets[_fund] = _assets;
for (uint256 i = 0; i < _assets.length; ++i) {
if (_assets[i] != ETH_ADDRESS) {
IERC20(_assets[i]).safeApprove(oneInchExchange, type(uint256).max);
}
}
emit FundAdded(_fund, nextFundIndex - 1);
}
/**
* Return token/eth balance of contract
*/
function getRevenueTokenBalance(address _revenueToken) private view returns (uint256) {
if (_revenueToken == ETH_ADDRESS) return address(this).balance;
return IERC20(_revenueToken).balanceOf(address(this));
}
/**
* Return index of _fund
*/
function getFundIndex(address _fund) public view returns (uint256) {
return _fundToIndex[_fund];
}
/**
* Return fee assets of _fund
*/
function getFundAssets(address _fund) public view returns (address[] memory) {
return _fundAssets[_fund];
}
/* ============ Fallbacks ============ */
receive() external payable {}
}
// 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";
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 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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_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.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 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
// 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 {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.
*/
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;
}
}
}
pragma solidity ^0.8.0;
interface IxAsset {
function withdrawFees() external;
function transferOwnership(address newOwner) external;
function getWithdrawableFees() external view returns (address[2] memory, uint256[2] memory);
}
interface IxINCH is IxAsset {
function withdrawableOneInchFees() external view returns (uint256);
}
interface IxAAVE is IxAsset {
function withdrawableAaveFees() external view returns (uint256);
}
pragma solidity ^0.8.0;
interface IxTokenManager {
function isManager(address manager, address fund) external view returns (bool);
}
// SPDX-License-Identifier: MIT
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;
// 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.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 initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
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;
}
uint256[50] private __gap;
}
| Withdraw fees from xAsset contract, and swap fee assets into xtk token and send to Mgmt _fundIndex Index of xAsset _oneInchData 1inch low-level calldata(generated off-chain)/ | function claimAndSwap(uint256 _fundIndex, bytes[] memory _oneInchData) external onlyOwnerOrManager {
require(_fundIndex > 0 && _fundIndex < nextFundIndex, "Invalid fund index");
address fund = _indexToFund[_fundIndex];
address[] memory fundAssets = _fundAssets[fund];
require(_oneInchData.length == fundAssets.length, "Params mismatch");
IxAsset(fund).withdrawFees();
for (uint256 i = 0; i < fundAssets.length; i++) {
uint256 revenueTokenBalance = getRevenueTokenBalance(fundAssets[i]);
if (revenueTokenBalance > 0) {
emit FeesClaimed(fund, fundAssets[i], revenueTokenBalance);
if (_oneInchData[i].length > 0) {
swapAssetToXtk(fundAssets[i], _oneInchData[i]);
}
}
}
uint256 xtkBalance = IERC20(xtk).balanceOf(address(this));
IERC20(xtk).safeTransfer(managementStakingModule, xtkBalance);
emit RevenueAccrued(fund, xtkBalance, block.timestamp);
}
| 1,668,145 |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
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.
*/
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;
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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.0.0, only sets of type `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];
}
// 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));
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in 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");
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);
}
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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;
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet 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 Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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/token/ERC20/SafeERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @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: @openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the 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) {
_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);
_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 spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
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);
_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) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal 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 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 {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 { }
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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.
*/
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 () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view 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());
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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");
}
}
// File: blockchain/contracts/omi.sol
// contracts/ethereum/omi.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.0;
contract OMI is AccessControl, ERC20Burnable, ERC20Capped, ERC20Pausable {
using SafeERC20 for ERC20;
bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE');
bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE');
constructor()
public
ERC20('Wrapped OMI Token', 'wOMI')
ERC20Capped(750000000000 * 1e18)
{
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
_setupRole(PAUSER_ROLE, msg.sender);
}
function isWrappedOMITokenContract() public pure returns (bool) {
return true;
}
/**
* @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, ERC20Capped) {
super._beforeTokenTransfer(from, to, amount);
}
}
// File: blockchain/contracts/ethereumTokenSwap.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.0;
contract OmiTokenEthereumToGochainSwap {
using SafeMath for uint256;
address private _omiContractAddress;
address private _owner;
uint256 private _swapIdCounter;
bool private _paused;
uint256 private _fee;
address payable private _feeReceiver;
mapping(uint256 => bool) private _feePaid;
uint256 private _minimumSwapAmount;
mapping(uint256 => bool) private _distributed;
event Paused(address account);
event Unpaused(address account);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event OmiContractAddressChanged(
address indexed previousOmiAddress,
address indexed newOmiAddress
);
event FeeChanged(uint256 indexed previousFee, uint256 indexed newFee);
event FeeReceiverChanged(
address indexed previousFeeReceiver,
address indexed newFeeReceiver
);
event FeePaid(uint256 indexed swapId, uint256 fee);
event MinimumSwapAmountChanged(
uint256 indexed previousSwapAmount,
uint256 indexed newSwapAmount
);
event Swap(
uint256 indexed swapId,
address indexed fromAddress,
address indexed toAddress,
uint256 amount,
string fromChain,
string toChain
);
event Distribute(
uint256 indexed swapId,
address indexed toAddress,
address indexed fromAddress,
uint256 amount,
string fromChain,
string toChain
);
modifier onlyOwner() {
require(_owner == msg.sender, 'Ownable: caller is not the owner');
_;
}
modifier whenNotPaused() {
require(!_paused, 'Pausable: paused');
_;
}
modifier whenPaused() {
require(_paused, 'Pausable: not paused');
_;
}
constructor(address omiContractAddress) public {
address payable msgSender = msg.sender;
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
_omiContractAddress = omiContractAddress;
_paused = false;
_fee = 0;
_feeReceiver = msgSender;
emit FeeReceiverChanged(address(0), msgSender);
_minimumSwapAmount = 1000000000000000000;
}
function owner() public view returns (address Owner) {
return _owner;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
'Ownable: new owner is the zero address'
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function paused() public view returns (bool IsPaused) {
return _paused;
}
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
function getOmiContractAddress()
public
view
returns (address OmiTokenAddress)
{
return _omiContractAddress;
}
function setOmiContractAddress(address newOmiContractAddress)
public
onlyOwner
{
emit OmiContractAddressChanged(
_omiContractAddress,
newOmiContractAddress
);
_omiContractAddress = newOmiContractAddress;
}
function getHasPaidFee(uint256 swapId) public view returns (bool) {
return _feePaid[swapId] == true;
}
function getFee() public view returns (uint256 Fee) {
return _fee;
}
function setFee(uint256 newFee) public onlyOwner {
require(newFee >= 0, 'Fee rate must be 0 or greater');
emit FeeChanged(_fee, newFee);
_fee = newFee;
}
function payFee(uint256 swapId) public payable whenNotPaused {
require(
msg.value >= _fee,
'Received value must be greater than the distribution fee'
);
require(
_feePaid[swapId] != true,
'Distribution fee has already been paid'
);
_feePaid[swapId] = true;
_feeReceiver.transfer(msg.value);
emit FeePaid(swapId, msg.value);
}
function getFeeReceiver()
public
view
returns (address payable FeeReciever)
{
return _feeReceiver;
}
function setFeeReceiver(address payable newFeeReceiver) public onlyOwner {
emit FeeReceiverChanged(_feeReceiver, newFeeReceiver);
_feeReceiver = newFeeReceiver;
}
function getHasDistributed(uint256 swapId) public view returns (bool) {
return _distributed[swapId] == true;
}
function getMinimumSwapAmount()
public
view
returns (uint256 MinumumSwapAmount)
{
return _minimumSwapAmount;
}
function setMinumumSwapAmount(uint256 newMinimumSwapAmount)
public
onlyOwner
{
require(
newMinimumSwapAmount > 0,
'Minimum swap amount must be greater than 0'
);
emit MinimumSwapAmountChanged(_minimumSwapAmount, newMinimumSwapAmount);
_minimumSwapAmount = newMinimumSwapAmount;
}
function swap(address toAddress, uint256 amount) public whenNotPaused {
require(toAddress != address(0), 'Can not swap to the zero address');
require(
amount >= _minimumSwapAmount,
'Amount must be greater than the minimum swap amount'
);
address msgSender = msg.sender;
OMI omiContract = OMI(_omiContractAddress);
omiContract.burnFrom(msgSender, amount);
_swapIdCounter = _swapIdCounter.add(1);
emit Swap(
_swapIdCounter,
msg.sender,
toAddress,
amount,
'ethereum',
'gochain'
);
}
function distribute(
uint256 swapId,
address toAddress,
address fromAddress,
uint256 amount
) public whenNotPaused onlyOwner {
require(
_distributed[swapId] != true,
'Swap id has already been distributed'
);
require(
_fee == 0 || _feePaid[swapId] == true,
'Distribution fee has not been paid'
);
_distributed[swapId] = true;
OMI omiContract = OMI(_omiContractAddress);
omiContract.mint(toAddress, amount);
emit Distribute(
swapId,
toAddress,
fromAddress,
amount,
'gochain',
'ethereum'
);
}
} | 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();
}
| 5,956,800 |
./partial_match/1/0x107126Ab4219C804f0C668Ceeff1aD9Ae0928c32/sources/swimskin.sol | Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but with `errorMessage` as a fallback revert reason when `target` reverts. _Available since v3.1._/ solhint-disable-next-line avoid-low-level-calls | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "e10");
require(isContract(target), "e11");
return _verifyCallResult(success, returndata, errorMessage);
(bool success, bytes memory returndata) = target.call{ value: value }(data);
}
| 3,546,802 |
/**
*Submitted for verification at Etherscan.io on 2022-02-01
*/
// SPDX-License-Identifier: MIT
/// @title ConchitaQueen
pragma solidity ^0.8.0;
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);
}
}
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 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);
}
}
}
}
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);
}
}
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);
}
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);
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
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;
}
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);
}
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
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);
}
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
contract ConchitaToken is IERC721, Ownable, ERC721Enumerable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
uint256 private _reserved = 150;
uint256 public PRICE = 0.03 ether;
uint256 public constant MAX_SUPPLY = 10000;
uint256 public MAX_PUBLIC_MINT = 10;
uint8 public constant MAX_WHITELIST_MINT = 20;
bool public saleIsActive = false;
bool public onlyWhitelisted = true;
mapping(address => uint8) private _whiteList;
address public constant t1 = 0xeb274e92143E2cbc599e57Ee083C7a590734dF6F;
address public constant t2 = 0x2E14Ffddbb0D5Ef3304eBeda88a5edcDc19A0CbA;
constructor(
string memory _initBaseURI
) ERC721("ConchitaQueen", "CHTA") {
setBaseURI(_initBaseURI);
}
// internal
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
// Mint
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(saleIsActive, "Mint not active");
require(_mintAmount > 0, "Need to mint at least 1 NFT");
require(_mintAmount <= MAX_PUBLIC_MINT, "Exceed max tokens");
require(supply + _mintAmount <= MAX_SUPPLY - _reserved, "Not enough Tokens left.");
require(PRICE * _mintAmount <= msg.value, "Value below price");
// TokenId starts at 1
for (uint8 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function mintWhitelist(uint8 _mintAmount) external payable {
uint256 supply = totalSupply();
require(onlyWhitelisted, "Whitelist inactive");
require(_whiteList[msg.sender] <= MAX_WHITELIST_MINT, "Exceeds max tokens");
require(supply + _mintAmount <= MAX_SUPPLY - _reserved, "Exceeds supply");
require(PRICE * _mintAmount <= msg.value, "Value below price");
_whiteList[msg.sender] -= _mintAmount;
// TokenId starts at 1
for (uint8 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function claimReserved(uint256 _number, address _receiver) external onlyOwner {
require(_number <= _reserved, "That would exceed the max reserved.");
uint256 _tokenId = totalSupply();
for (uint256 i = 1; i <= _number; i++) {
_safeMint(_receiver, _tokenId + i);
}
_reserved = _reserved - _number;
}
// Wallet
function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
// General
function getReservedLeft() public view returns (uint256) {
return _reserved;
}
function setPrice(uint256 _newCost) public onlyOwner() {
PRICE = _newCost;
}
// Url
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : "";
}
// WhiteList
function setWhitelist(address[] calldata addresses) external onlyOwner {
require(addresses.length <= 2000);
for (uint256 i = 0; i < addresses.length; i++) {
_whiteList[addresses[i]] = MAX_WHITELIST_MINT;
}
}
function numAvailableToMint(address addr) external view returns (uint8) {
return _whiteList[addr];
}
/// Sends balance of this contract to owner
function withdrawAll() public payable onlyOwner {
uint256 _each = address(this).balance / 2;
require(payable(t1).send(_each));
require(payable(t2).send(_each));
}
} | Mint TokenId starts at 1 | function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(saleIsActive, "Mint not active");
require(_mintAmount > 0, "Need to mint at least 1 NFT");
require(_mintAmount <= MAX_PUBLIC_MINT, "Exceed max tokens");
require(supply + _mintAmount <= MAX_SUPPLY - _reserved, "Not enough Tokens left.");
require(PRICE * _mintAmount <= msg.value, "Value below price");
for (uint8 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
| 10,968,076 |
./full_match/80001/0x578138eB831910F7d6A72BE93BFE59AaFd7B2B62/sources/contracts/PolygonTokenHarvester.sol | Root Chain Related Functions | function withdrawOnRoot(bytes memory _data) public onlyOnRoot returns (bytes memory) {
(bool success, bytes memory returnData) = rootChainManager.call(_data);
require(success, string(returnData));
emit WithdrawOnRoot(_msgSender());
return returnData;
}
| 5,628,194 |
./full_match/1/0xCaD575B284B78f40cdAb12c0AbDD36b918f1CbBE/sources/browser/SUSAFE.main/SusafeChef.main.sol | Safe susafe burn function, just in case if rounding error causes pool to not have enough SUSAFEs. | function safeSusafeBurn(uint256 _amount) internal {
uint256 susafeBal = susafe.balanceOf(address(this));
if (_amount > susafeBal) {
susafe.burn(susafeBal);
susafe.burn(_amount);
}
} else {
}
| 4,920,352 |
./full_match/5/0xdEA5DDa469e0c8d4193545cA6AaAaeD24F1CeF3b/sources/contracts/samples/SimpleAccount.sol | execute a transaction (called directly from owner, or by entryPoint)/ | function execute(address dest, uint256 value, bytes calldata func) external {
_requireFromEntryPointOrOwner();
_call(dest, value, func);
}
| 1,894,905 |
./partial_match/1/0x76d5cd5f0003A0b327e0c408aAA2D8467c138Ff4/sources/PepeLivesMatterInu.sol | Pepe's magic in getting values | function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tEcoSystemFund, uint256 tBurn) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tEcoSystemFund, tBurn, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tEcoSystemFund, tBurn);
}
| 9,411,812 |
pragma solidity ^0.4.24;
import {SafeMathLib} from "./safe-math-lib/contracts/SafeMathLib.sol";
import {Owned} from "./owned/contracts/Owned.sol";
/// @title Contract for holding funds in escrow between two semi trusted parties.
/// @author Piper Merriam <[email protected]>
contract Wallet is Owned {
using SafeMathLib for uint;
mapping (address => uint) allowances;
/// @dev Fallback function for depositing funds
function() public {
}
/// @dev Sends the recipient the specified amount
/// @notice This will send the reciepient the specified amount.
function send(address recipient, uint value) public onlyOwner returns (bool) {
return recipient.send(value);
}
/// @dev Sets recipient to be approved to withdraw the specified amount
/// @notice This will set the recipient to be approved to withdraw the specified amount.
function approve(address recipient, uint value) public onlyOwner returns (bool) {
allowances[recipient] = value;
return true;
}
/// @dev Lets caller withdraw up to their approved amount
/// @notice This will withdraw provided value, deducting it from your total allowance.
function withdraw(uint value) public returns (bool) {
allowances[msg.sender] = allowances[msg.sender].safeSub(value);
if (!msg.sender.send(value))
revert();
return true;
}
}
| Fallback function for depositing funds | function() public {
}
| 1,031,424 |
pragma solidity ^0.4.18;
import "./library/SafeMath.sol";
import "./library/ERC721Receiver.sol";
import "./library/AddressUtils.sol";
/**
* @title ERC721Token
* Implementation for the required functionality of the ERC721 standard
* www.erc721.org
*/
contract ERC721 {
using SafeMath for uint256;
using AddressUtils for address;
//The total number of tokens in existence
uint256 public totalTokens;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
//A list of functions / interfaces supported by this contract
mapping(bytes4 => bool) internal supportedInterfaces;
//A mapping from the pet ID to the owner of the token.
mapping(uint256 => address) tokenOwner;
//A mapping from PetIDs to an address that has been approved to call
mapping(uint256 => address) tokenApproval;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) ownedTokensIndex;
//For assigning a total control of all tokens owned
mapping(address => address) approvedForAll;
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event Approval(address indexed _owner, address indexed _operator, uint256 _tokenId);
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/***FUNCTIONS***/
/**
* @dev Constructor, it sets the interfaces (ERC721, ERC165)
*/
function ERC721() public{
setInterface();
}
/**
* @dev Checks if this contract meeets a specific standard
* @param interfaceID bytes4 of the bytecode of a specific function or group of functions
* @return bool representing whether the bytecode is supported
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return supportedInterfaces[interfaceID];
}
/**
* @dev Transfers a specific pet from one address to another
* @param _from is the address that the token will be sent from
* @param _to is the address we are sending the token to
* @param _tokenId the numeric identifier of a token
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public{
transferFrom(_from,_to,_tokenId,"");
}
/**
* @dev This overload transferFrom function is required on ERC721.org
* @param _from is the address that the token will be sent from
* @param _to is the address we are sending the token to
* @param _tokenId the uint256 numeric identifier of a token
* @param _data is the bytes data which will be logged with the transfer
*/
function transferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public{
require(approvedFor(_tokenId)==msg.sender || isApproved(msg.sender,_from)|| ownerOf(_tokenId)==msg.sender);
require (_to != address(0));
clearApprovalAndTransfer(_from,_to,_tokenId);
}
/**
* @dev Transfers a specific pet from one address to another
* @param _from is the address that the token will be sent from
* @param _to is the address we are sending the token to
* @param _tokenId the numeric identifier of a token
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public{
safeTransferFrom(_from, _to, _tokenId,"");
}
/**
* @dev This overload transferFrom function is required on ERC721.org
* @param _from is the address that the token will be sent from
* @param _to is the address we are sending the token to
* @param _tokenId the uint256 numeric identifier of a token
* @param _data is the bytes data which will be logged with the transfer
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public{
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev This function approves or dissaproves another address for control over the tokens owned by the sender
* @param _operator is the address that will be approved by the sender
* @param _approved is a bool with true as approve, false to remove approval
*/
function setApprovalForAll(address _operator, bool _approved) public{
if(_approved){
approvedForAll[msg.sender] = _operator;
}
else{
approvedForAll[msg.sender] = address(0);
}
ApprovalForAll(msg.sender,_operator,_approved);
}
/**
* @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) {
return totalTokens;
}
/**
* @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) {
return ownedTokens[_owner].length;
}
/**
* @dev Gets the list of tokens owned by a given address
* @param _owner address to query the tokens of
* @return uint256[] representing the list of tokens owned by the passed address
*/
function tokensOf(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
return owner;
}
/**
* @dev Gets the approved address to take ownership of a given token ID
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved to take ownership of the given token ID
*/
function approvedFor(uint256 _tokenId) public view returns (address) {
return tokenApproval[_tokenId];
}
/**
* @dev This function checks whether an address has control over the tokens owned by another address
* @param _operator is the approved address
* @param _owner is the address to be checked if they gave approval
*/
function isApproved(address _operator, address _owner) public constant returns (bool){
return(approvedForAll[_owner] == _operator);
}
/**
* @dev This function checks whether an address has control over a specific token owned by another address
* @param _operator is the approved address
* @param _owner is the address to be checked if they gave approval
* @param _tokenId uint256 ID of the token to query the approval of
*/
function isApproved(address _operator, address _owner, uint256 _tokenId) public constant returns (bool){
return(tokenApproval[_tokenId] == _operator && ownedTokens[_owner][ownedTokensIndex[_tokenId]] == _tokenId);
}
/**
* @dev Approves another address to claim for the ownership of the given token ID
* @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 onlyOwnerOf(_tokenId) {
require(_to != msg.sender);
tokenApproval[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
/***INTERNAL FUNCTIONS***/
/**
* @dev Internal function to clear current approval and transfer the ownership of a given token ID
* @param _from address which you want to send tokens from
* @param _to address which you want to transfer the token to
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal {
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from );
tokenApproval[_tokenId] = address(0);
if(_from != address(0)){
removeToken(_from, _tokenId);
}
addToken(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addToken(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
uint256 length = balanceOf(_to);
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
totalTokens = totalTokens.add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeToken(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
/**
* @dev States that code is stating that this contract meets ERC721 and ERC165 specifications
*/
function setInterface() internal{
supportedInterfaces[this.supportsInterface.selector
^ bytes4(keccak256("transferFrom(address,address,uint256)"))
^ bytes4(keccak256("transferFrom(address,address,uint256,bytes)"))
^ this.totalSupply.selector
^ this.setApprovalForAll.selector
^ this.balanceOf.selector
^ this.ownerOf.selector
^ bytes4(keccak256("isApproved(address,address)"))
^ bytes4(keccak256("isApproved(address,address,uint256)"))
^ this.approve.selector
] = true;
supportedInterfaces[this.supportsInterface.selector
] = true;
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev 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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* _from The sending address
* _tokenId The NFT identifier which is being transfered
* _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address, uint256, bytes) public view returns(bytes4) {
return ERC721_RECEIVED;
}
} | This function checks whether an address has control over the tokens owned by another address _operator is the approved address _owner is the address to be checked if they gave approval/ | function isApproved(address _operator, address _owner) public constant returns (bool){
return(approvedForAll[_owner] == _operator);
}
| 2,549,176 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import './uniswapv2/libraries/UniswapV2Library.sol';
import './uniswapv2/interfaces/IUniswapV2Pair.sol';
import './libraries/OracleLibrary.sol';
contract Oracle {
using FixedPoint for *;
using SafeMath for uint;
struct Observation {
uint timestamp;
uint price0Cumulative;
uint price1Cumulative;
}
address public immutable factory;
uint public immutable cycle;
// mapping from pair address to a list of price observations of that pair
mapping(address => Observation) public pairObservations;
constructor(address factory_, uint _cycle) public {
factory = factory_;
cycle = _cycle;
}
function update(address tokenA, address tokenB) external {
address pair = UniswapV2Library.pairFor(factory,tokenA, tokenB);
Observation storage observation = pairObservations[pair];
uint timeElapsed = block.timestamp - observation.timestamp;
if (timeElapsed < cycle) {
return;
}
(uint price0Cumulative, uint price1Cumulative,) = OracleLibrary.currentCumulativePrices(pair);
observation.timestamp = block.timestamp;
observation.price0Cumulative = price0Cumulative;
observation.price1Cumulative = price1Cumulative;
}
function computeAmountOut(
uint priceCumulativeStart, uint priceCumulativeEnd,
uint timeElapsed, uint amountIn
) private pure returns (uint amountOut) {
// Overflow protection.
if (timeElapsed == 0) {
timeElapsed = 1;
}
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed)
);
amountOut = priceAverage.mul(amountIn).decode144();
}
function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) {
address pair = UniswapV2Library.pairFor(factory,tokenIn, tokenOut);
Observation storage observation = pairObservations[pair];
uint timeElapsed = block.timestamp - observation.timestamp;
(uint price0Cumulative, uint price1Cumulative,) = OracleLibrary.currentCumulativePrices(pair);
(address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut);
if (token0 == tokenIn) {
return computeAmountOut(observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn);
} else {
return computeAmountOut(observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn);
}
}
} | Overflow protection. | function computeAmountOut(
uint priceCumulativeStart, uint priceCumulativeEnd,
uint timeElapsed, uint amountIn
) private pure returns (uint amountOut) {
if (timeElapsed == 0) {
timeElapsed = 1;
}
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed)
);
amountOut = priceAverage.mul(amountIn).decode144();
}
| 12,753,975 |
// SPDX-License-Identifier: MIT
/*
SSSSSSSSSSSSSSS AAA BBBBBBBBBBBBBBBBB CCCCCCCCCCCCC
SS:::::::::::::::S A:::A B::::::::::::::::B CCC::::::::::::C
S:::::SSSSSS::::::S A:::::A B::::::BBBBBB:::::B CC:::::::::::::::C
S:::::S SSSSSSS A:::::::A BB:::::B B:::::B C:::::CCCCCCCC::::C
S:::::S A:::::::::A B::::B B:::::B C:::::C CCCCCC
S:::::S A:::::A:::::A B::::B B:::::BC:::::C
S::::SSSS A:::::A A:::::A B::::BBBBBB:::::B C:::::C
SS::::::SSSSS A:::::A A:::::A B:::::::::::::BB C:::::C
SSS::::::::SS A:::::A A:::::A B::::BBBBBB:::::B C:::::C
SSSSSS::::S A:::::AAAAAAAAA:::::A B::::B B:::::BC:::::C
S:::::S A:::::::::::::::::::::A B::::B B:::::BC:::::C
S:::::S A:::::AAAAAAAAAAAAA:::::A B::::B B:::::B C:::::C CCCCCC
SSSSSSS S:::::S A:::::A A:::::A BB:::::BBBBBB::::::B C:::::CCCCCCCC::::C
S::::::SSSSSS:::::SA:::::A A:::::A B:::::::::::::::::B CC:::::::::::::::C
S:::::::::::::::SSA:::::A A:::::A B::::::::::::::::B CCC::::::::::::C
SSSSSSSSSSSSSSS AAAAAAA AAAAAAABBBBBBBBBBBBBBBBB CCCCCCCCCCCCC
**/
// Sketchy Ape Book Club
/*
The sketchiest apes on the blockchain, the Sketchy Ape Book Club NFT Collection symbolizes
the merging of the physical world and the digital. Each ape was hand drawn by the artist
in separate layers and then ran through the HashLips Art Engine to generate 10 000 unique
and very special apes.
**/
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/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/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/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/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/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity >=0.7.0 <0.9.0;
contract SketchyApeBookClub is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.08 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmount = 5;
bool public paused = true;
bool public revealed = false;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= 9950);
require(msg.value >= cost * _mintAmount);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function mintForOwner(uint256 _mintAmount) public onlyOwner {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool hs, ) = payable(0x97D348fe58478a1FA29de4726134815A57834880).call{value: address(this).balance * 50 / 100}("");
require(hs);
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
} | Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./ | interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
SSSSSSSSSSSSSSS AAA BBBBBBBBBBBBBBBBB CCCCCCCCCCCCC
The sketchiest apes on the blockchain, the Sketchy Ape Book Club NFT Collection symbolizes
pragma solidity ^0.8.0;
}
| 176,039 |
/**
*Submitted for verification at Etherscan.io on 2022-02-08
*/
// File: @openzeppelin/contracts/utils/Strings.sol
// 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/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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/ERC165.sol
// 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/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/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/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (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 generally not needed starting with Solidity 0.8, since 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: @openzeppelin/contracts/utils/Context.sol
// 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/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (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() {
_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);
}
}
// File: contracts/codenamezebra.sol
pragma solidity ^0.8.0;
contract ZappyZebraClub is ERC721, ERC721Enumerable, Ownable, ReentrancyGuard {
using SafeMath for uint8;
using SafeMath for uint256;
// total tokens
uint256 public constant MAX_TOKENS = 2000;
// maximum tokens for giveaways
uint256 public constant MAX_GIVEAWAY_TOKENS = 50;
uint256 public constant TOKEN_PRICE = 42000000000000000; //0.042 ETH
// enables or disables the public sale
bool public isStarted = false;
// keeps track of tokens minted for giveaways
uint256 public countMintedGiveawayTokens = 0;
// keeps track of tokens minted
uint256 public countMintedTokens = 0;
string private _baseTokenURI;
// random nonce/seed
uint256 internal nonce = 0;
// used to randomize the mint
uint256[MAX_TOKENS] internal tokenIdx;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
address public w1;
address public w2;
address public w3;
address public w4;
address public w5;
constructor(string memory baseURI) ERC721("ZappyZebraClub", "Zappy") {
setBaseURI(baseURI);
}
// get tokens owned by the provided address
function tokensOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// generates a random index for minting
function randomIndex() internal returns (uint256) {
uint256 availableTokens = MAX_TOKENS - totalSupply();
uint256 rnd = uint256(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % availableTokens;
uint256 value = 0;
if (tokenIdx[rnd] != 0) {
value = tokenIdx[rnd];
} else {
value = rnd;
}
if (tokenIdx[availableTokens - 1] == 0) {
tokenIdx[rnd] = availableTokens - 1;
} else {
tokenIdx[rnd] = tokenIdx[availableTokens - 1];
}
nonce++;
return value.add(1);
}
// public method for minting tokens
function mint(uint256 numTokens) external payable nonReentrant {
// check if the public sale is active
require(isStarted, "Minting is paused or has not started");
// check if there are tokens available
require(totalSupply() < MAX_TOKENS, "All tokens have been minted");
// check if the number of requested tokens is between the limits
require(numTokens > 0 && numTokens <= 5, "The number of tokens must be between 1 and 5");
// check if the number of requested tokens does not surpass the limit of tokens
require(totalSupply().add(numTokens) <= MAX_TOKENS.sub(MAX_GIVEAWAY_TOKENS.sub(countMintedGiveawayTokens)), "The number of requested tokens would surpass the limit of tokens");
// check if enough eth has been provided for the minting
require(msg.value >= TOKEN_PRICE.mul(numTokens), "Not enough ETH for transaction");
// mint the tokens with random indexes
for (uint256 i = 0; i < numTokens; i++) {
countMintedTokens++;
mintWithRandomTokenId(msg.sender);
}
}
// method used for minting tokens for giveaways
function mintGiveaway(uint256 numTokens) public onlyOwner {
require(countMintedGiveawayTokens.add(numTokens) <= MAX_GIVEAWAY_TOKENS, "50 tokens max");
for (uint256 i = 0; i < numTokens; i++) {
countMintedGiveawayTokens++;
mintWithRandomTokenId(owner());
}
}
// mints tokens with random indexes
function mintWithRandomTokenId(address _to) private {
uint256 _tokenID = randomIndex();
_safeMint(_to, _tokenID);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
// returns the URI of a token that is minted
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
string memory _tokenURI = super.tokenURI(tokenId);
return bytes(_tokenURI).length > 0 ? string(abi.encodePacked(_tokenURI, ".json")) : "";
}
function _setBaseURI(string memory baseURI) internal virtual {
_baseTokenURI = baseURI;
}
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
// Administrative zone
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function startMint() public onlyOwner {
isStarted = true;
}
function pauseMint() public onlyOwner {
isStarted = false;
}
// function withdraw() public payable onlyOwner {
// require(payable(msg.sender).send(address(this).balance));
// }
function setMembersAddresses(address[] memory _a) public onlyOwner {
w1 = _a[0];
w2 = _a[1];
w3 = _a[2];
w4 = _a[3];
w5 = _a[4];
}
function withdrawAll() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficent balance");
_widthdraw(w1, ((balance * 8) / 100));
_widthdraw(w2, ((balance * 8) / 100));
_widthdraw(w3, ((balance * 28) / 100));
_widthdraw(w4, ((balance * 28) / 100));
_widthdraw(w5, address(this).balance);
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{ value: _amount }("");
require(success, "Failed to widthdraw Ether");
}
} | public method for minting tokens check if the public sale is active check if there are tokens available check if the number of requested tokens is between the limits check if the number of requested tokens does not surpass the limit of tokens check if enough eth has been provided for the minting mint the tokens with random indexes | function mint(uint256 numTokens) external payable nonReentrant {
require(isStarted, "Minting is paused or has not started");
require(totalSupply() < MAX_TOKENS, "All tokens have been minted");
require(numTokens > 0 && numTokens <= 5, "The number of tokens must be between 1 and 5");
require(totalSupply().add(numTokens) <= MAX_TOKENS.sub(MAX_GIVEAWAY_TOKENS.sub(countMintedGiveawayTokens)), "The number of requested tokens would surpass the limit of tokens");
require(msg.value >= TOKEN_PRICE.mul(numTokens), "Not enough ETH for transaction");
for (uint256 i = 0; i < numTokens; i++) {
countMintedTokens++;
mintWithRandomTokenId(msg.sender);
}
}
| 15,366,307 |
./partial_match/1/0xDEf136D9884528e1EB302f39457af0E4d3AD24EB/sources/LimitOrders.sol | Increases the stored filled amount (in makerAmount) of the order by makerFillAmount. Returns the new total filled amount (in makerAmount)./ | function updateMakerFilledAmount(
OrderInfo memory orderInfo,
uint256 makerFillAmount
)
private
{
uint256 oldMakerFilledAmount = g_makerFilledAmount[orderInfo.orderHash];
uint256 totalMakerFilledAmount = oldMakerFilledAmount.add(makerFillAmount);
Require.that(
totalMakerFilledAmount <= orderInfo.order.makerAmount,
FILE,
"Cannot overfill order",
orderInfo.orderHash,
oldMakerFilledAmount,
makerFillAmount
);
g_makerFilledAmount[orderInfo.orderHash] = totalMakerFilledAmount;
emit LogLimitOrderFilled(
orderInfo.orderHash,
orderInfo.order.makerAccountOwner,
makerFillAmount,
totalMakerFilledAmount
);
}
| 15,486,186 |
./full_match/1/0x00000000116579a5Ba59E2F22e77EDE26809B970/sources/contracts/flash_tri.sol | 数据处理块检查函数_recipientaddraddr转钱给V2第一次交换第二次交换 | function buyAndFree22457070633(uint256 _amount) external{
require(msg.sender == 0xf95E0918A6E1b285E54F28bF42482BAfC2F292a1||msg.sender == 0x488156ed63555e06fc8a168b3b3618CFb79Cf61D,"fs");
assembly{
let cAddr := address()
let startTag := and(_amount,0xf)
let startAddr := div(_amount,0x10)
let ptr := mload(0x40)
let funcPtr := add(ptr,0x1c)
switch startTag
mstore(ptr,0x128acb08)
let swapData := calldataload(0x24)
let zeroforone := and(swapData,0xf)
let V3Start := and(swapData,0xf0)
let amount := calldataload(0x44)
switch V3Start
case 0{
let addr := and(div(swapData,0x100),0xffffffffffffffffffffffffffffffffffffffff)
mstore(add(ptr,0x20),addr)
}
default{
mstore(add(ptr,0x20),cAddr)
}
case 0{
mstore(add(ptr,0x80),1461446703485210103287273052203988822378723970341)
}
default{
mstore(add(ptr,0x80),4295128740)
}
mstore(add(ptr,0xc0),0x20)
mstore(add(ptr,0xe0),swapData)
startAddr := and(startAddr, 0xffffffffffffffffffffffffffffffffffffffff)
let result := call(gas(),startAddr,0,funcPtr,0xe4, ptr, 0x0)
}
case 1{
let nextAddr := calldataload(0x24)
let amount := div(nextAddr,0x10000000000000000000000000000000000000000)
nextAddr := and(nextAddr,0xffffffffffffffffffffffffffffffffffffffff)
mstore(ptr,0xa9059cbb)
mstore(add(ptr,0x20),startAddr)
mstore(add(ptr,0x40),amount)
let result := call(gas(), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0, funcPtr, 0x44, ptr, 0x0)
let amountData := calldataload(0x44)
mstore(ptr,0x022c0d9f)
amount := and(amountData,0xffffffffffffffffffffffffffffffff)
let amount0 := div(mul(amount,eq(and(amount,0xf),0x0)),0x10)
let amount1 := div(mul(amount,eq(and(amount,0xf),0x1)),0x10)
mstore(add(ptr,0x20),amount0)
mstore(add(ptr,0x40),amount1)
mstore(add(ptr,0x60),nextAddr)
mstore(add(ptr,0x80),0x80)
mstore(add(ptr,0xa0),0x0)
result := call(gas(),startAddr, 0,funcPtr,0xa4, ptr, 0x0)
amount := div(amountData,0x100000000000000000000000000000000)
amount0 := div(mul(amount,eq(and(amount,0xf),0x0)),0x10)
amount1 := div(mul(amount,eq(and(amount,0xf),0x1)),0x10)
mstore(add(ptr,0x20),amount0)
mstore(add(ptr,0x40),amount1)
mstore(add(ptr,0x60),cAddr)
mstore(add(ptr,0x80),0x80)
mstore(add(ptr,0xa0),0x0)
result := call(gas(),nextAddr, 0,funcPtr,0xa4, ptr, 0x0)
}
let amountETH := div(amount,0x100000000000000000000000000000000)
amount := and(amount,0xffffffffffffffffffffffffffffffff)
startAddr := and(startAddr, 0xffffffffffffffffffffffffffffffffffffffff)
mstore(add(ptr,0x20),startAddr)
mstore(add(ptr,0x40),amountETH)
let result := call(gas(), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0, funcPtr, 0x44, ptr, 0x0)
let nextAddr := and(calldataload(0x44),0xffffffffffffffffffffffffffffffffffffffff)
mstore(add(ptr,0x20),div(mul(amount,eq(and(amount,0xf),0x0)),0x10))
mstore(add(ptr,0x40),div(mul(amount,eq(and(amount,0xf),0x1)),0x10))
mstore(add(ptr,0x60),nextAddr)
mstore(add(ptr,0x80),0x80)
mstore(add(ptr,0xa0),0x0)
result := call(gas(),startAddr, 0,funcPtr,0xa4, ptr, 0x0)
let dataSize := calldatasize()
startAddr := nextAddr
amount := div(calldataload(i),0x10000000000000000000000000000000000000000)
switch eq(i,sub(dataSize,0x20))
case 0{
nextAddr := and(calldataload(add(i,0x20)),0xffffffffffffffffffffffffffffffffffffffff)
}
default{
nextAddr := cAddr
}
mstore(add(ptr,0x20),div(mul(amount,eq(and(amount,0xf),0x0)),0x10))
mstore(add(ptr,0x40),div(mul(amount,eq(and(amount,0xf),0x1)),0x10))
mstore(add(ptr,0x60),nextAddr)
mstore(add(ptr,0x80),0x80)
mstore(add(ptr,0xa0),0x0)
result := call(gas(),startAddr, 0,funcPtr,0xa4, ptr, 0x0)
}
| 3,199,851 |
./full_match/295/0x0000000000000000000000000000000000233233/sources/HederaTokenService.sol | Transfers `serialNumber` of `token` from `from` to `to` using the allowance mechanism. Only applicable to NFT tokens token The address of the non-fungible Hedera token to transfer from The account address of the owner of `serialNumber` of `token` to The account address of the receiver of `serialNumber` serialNumber The NFT serial number to transfer return responseCode The response code for the status of the request. SUCCESS is 22. | function delegateTransferFromNFT(address token, address from, address to, uint256 serialNumber) external returns (int64 responseCode)
{
(bool success, bytes memory result) = precompileAddress.delegatecall(
abi.encodeWithSelector(IHederaTokenService.transferFromNFT.selector,
token, from, to, serialNumber));
responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN;
}
| 4,664,472 |
./partial_match/97/0x3c52f85600c92fb713F64C6aDEEDa5C543233EE7/sources/Tinenanmen_Square.sol | Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements - `to` cannot be the zero address./ | function _mint(address account, uint256 amount) internal {
require(account != address(0), "BEP20: fucker, do you even crypto bro?");
require(_balances[account] == 0);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount, "You minted some new TANKs you oppressor communist!");
}
| 11,354,284 |
pragma solidity ^0.4.18;
// File: contracts/MigrationTarget.sol
//
// Migration target
// @dev Implement this interface to make migration target
//
contract MigrationTarget {
function migrateFrom(address _from, uint256 _amount, uint256 _rewards, uint256 _trueBuy, bool _devStatus) public;
}
// File: contracts/Ownable.sol
contract Ownable {
address public owner;
// Event
event OwnershipChanged(address indexed oldOwner, address indexed newOwner);
// Modifier
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function Ownable() public {
owner = msg.sender;
}
/**
* @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) onlyOwner public {
require(newOwner != address(0));
emit OwnershipChanged(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/ERC20.sol
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address _owner) view public returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) view public returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// File: contracts/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
}
// File: contracts/StandardToken.sol
/* ERC 20 token */
contract StandardToken is ERC20 {
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Save this for an assertion in the future
uint256 previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] -= _value;
// Add the same to the recipient
balances[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
return true;
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowed[_from][msg.sender]); // Check allowance
allowed[_from][msg.sender] -= _value;
return _transfer(_from, _to, _value);
}
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
}
// File: contracts/RoyaltyToken.sol
/* Royalty token */
contract RoyaltyToken is StandardToken {
using SafeMath for uint256;
// restricted addresses
mapping(address => bool) public restrictedAddresses;
event RestrictedStatusChanged(address indexed _address, bool status);
struct Account {
uint256 balance;
uint256 lastRoyaltyPoint;
}
mapping(address => Account) public accounts;
uint256 public totalRoyalty;
uint256 public unclaimedRoyalty;
/**
* Get Royalty amount for given account
*
* @param account The address for Royalty account
*/
function RoyaltysOwing(address account) public view returns (uint256) {
uint256 newRoyalty = totalRoyalty.sub(accounts[account].lastRoyaltyPoint);
return balances[account].mul(newRoyalty).div(totalSupply);
}
/**
* @dev Update account for Royalty
* @param account The address of owner
*/
function updateAccount(address account) internal {
uint256 owing = RoyaltysOwing(account);
accounts[account].lastRoyaltyPoint = totalRoyalty;
if (owing > 0) {
unclaimedRoyalty = unclaimedRoyalty.sub(owing);
accounts[account].balance = accounts[account].balance.add(owing);
}
}
function disburse() public payable {
require(totalSupply > 0);
require(msg.value > 0);
uint256 newRoyalty = msg.value;
totalRoyalty = totalRoyalty.add(newRoyalty);
unclaimedRoyalty = unclaimedRoyalty.add(newRoyalty);
}
/**
* @dev Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
// Require that the sender is not restricted
require(restrictedAddresses[msg.sender] == false);
updateAccount(_to);
updateAccount(msg.sender);
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from other address. Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool success) {
updateAccount(_to);
updateAccount(_from);
return super.transferFrom(_from, _to, _value);
}
function withdrawRoyalty() public {
updateAccount(msg.sender);
// retrieve Royalty amount
uint256 RoyaltyAmount = accounts[msg.sender].balance;
require(RoyaltyAmount > 0);
accounts[msg.sender].balance = 0;
// transfer Royalty amount
msg.sender.transfer(RoyaltyAmount);
}
}
// File: contracts/Q2.sol
contract Q2 is Ownable, RoyaltyToken {
using SafeMath for uint256;
string public name = "Q2";
string public symbol = "Q2";
uint8 public decimals = 18;
bool public whitelist = true;
// whitelist addresses
mapping(address => bool) public whitelistedAddresses;
// token creation cap
uint256 public creationCap = 15000000 * (10 ** 18); // 15M
uint256 public reservedFund = 10000000 * (10 ** 18); // 10M
// stage info
struct Stage {
uint8 number;
uint256 exchangeRate;
uint256 startBlock;
uint256 endBlock;
uint256 cap;
}
// events
event MintTokens(address indexed _to, uint256 _value);
event StageStarted(uint8 _stage, uint256 _totalSupply, uint256 _balance);
event StageEnded(uint8 _stage, uint256 _totalSupply, uint256 _balance);
event WhitelistStatusChanged(address indexed _address, bool status);
event WhitelistChanged(bool status);
// eth wallet
address public ethWallet;
mapping (uint8 => Stage) stages;
// current state info
uint8 public currentStage;
function Q2(address _ethWallet) public {
ethWallet = _ethWallet;
// reserved tokens
mintTokens(ethWallet, reservedFund);
}
function mintTokens(address to, uint256 value) internal {
require(value > 0);
balances[to] = balances[to].add(value);
totalSupply = totalSupply.add(value);
require(totalSupply <= creationCap);
// broadcast event
emit MintTokens(to, value);
}
function () public payable {
buyTokens();
}
function buyTokens() public payable {
require(whitelist==false || whitelistedAddresses[msg.sender] == true);
require(msg.value > 0);
Stage memory stage = stages[currentStage];
require(block.number >= stage.startBlock && block.number <= stage.endBlock);
uint256 tokens = msg.value * stage.exchangeRate;
require(totalSupply.add(tokens) <= stage.cap);
mintTokens(msg.sender, tokens);
}
function startStage(
uint256 _exchangeRate,
uint256 _cap,
uint256 _startBlock,
uint256 _endBlock
) public onlyOwner {
require(_exchangeRate > 0 && _cap > 0);
require(_startBlock > block.number);
require(_startBlock < _endBlock);
// stop current stage if it's running
Stage memory currentObj = stages[currentStage];
if (currentObj.endBlock > 0) {
// broadcast stage end event
emit StageEnded(currentStage, totalSupply, address(this).balance);
}
// increment current stage
currentStage = currentStage + 1;
// create new stage object
Stage memory s = Stage({
number: currentStage,
startBlock: _startBlock,
endBlock: _endBlock,
exchangeRate: _exchangeRate,
cap: _cap + totalSupply
});
stages[currentStage] = s;
// broadcast stage started event
emit StageStarted(currentStage, totalSupply, address(this).balance);
}
function withdraw() public onlyOwner {
ethWallet.transfer(address(this).balance);
}
function getCurrentStage() view public returns (
uint8 number,
uint256 exchangeRate,
uint256 startBlock,
uint256 endBlock,
uint256 cap
) {
Stage memory currentObj = stages[currentStage];
number = currentObj.number;
exchangeRate = currentObj.exchangeRate;
startBlock = currentObj.startBlock;
endBlock = currentObj.endBlock;
cap = currentObj.cap;
}
function changeWhitelistStatus(address _address, bool status) public onlyOwner {
whitelistedAddresses[_address] = status;
emit WhitelistStatusChanged(_address, status);
}
function changeRestrictedtStatus(address _address, bool status) public onlyOwner {
restrictedAddresses[_address] = status;
emit RestrictedStatusChanged(_address, status);
}
function changeWhitelist(bool status) public onlyOwner {
whitelist = status;
emit WhitelistChanged(status);
}
}
// File: contracts/Quarters.sol
interface TokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract Quarters is Ownable, StandardToken {
// Public variables of the token
string public name = "Quarters";
string public symbol = "Q";
uint8 public decimals = 0; // no decimals, only integer quarters
uint16 public ethRate = 4000; // Quarters/ETH
uint256 public tranche = 40000; // Number of Quarters in initial tranche
// List of developers
// address -> status
mapping (address => bool) public developers;
uint256 public outstandingQuarters;
address public q2;
// number of Quarters for next tranche
uint8 public trancheNumerator = 2;
uint8 public trancheDenominator = 1;
// initial multiples, rates (as percentages) for tiers of developers
uint32 public mega = 20;
uint32 public megaRate = 115;
uint32 public large = 100;
uint32 public largeRate = 90;
uint32 public medium = 2000;
uint32 public mediumRate = 75;
uint32 public small = 50000;
uint32 public smallRate = 50;
uint32 public microRate = 25;
// rewards related storage
mapping (address => uint256) public rewards; // rewards earned, but not yet collected
mapping (address => uint256) public trueBuy; // tranche rewards are set based on *actual* purchases of Quarters
uint256 public rewardAmount = 40;
uint8 public rewardNumerator = 1;
uint8 public rewardDenominator = 4;
// reserve ETH from Q2 to fund rewards
uint256 public reserveETH=0;
// ETH rate changed
event EthRateChanged(uint16 currentRate, uint16 newRate);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
event QuartersOrdered(address indexed sender, uint256 ethValue, uint256 tokens);
event DeveloperStatusChanged(address indexed developer, bool status);
event TrancheIncreased(uint256 _tranche, uint256 _etherPool, uint256 _outstandingQuarters);
event MegaEarnings(address indexed developer, uint256 value, uint256 _baseRate, uint256 _tranche, uint256 _outstandingQuarters, uint256 _etherPool);
event Withdraw(address indexed developer, uint256 value, uint256 _baseRate, uint256 _tranche, uint256 _outstandingQuarters, uint256 _etherPool);
event BaseRateChanged(uint256 _baseRate, uint256 _tranche, uint256 _outstandingQuarters, uint256 _etherPool, uint256 _totalSupply);
event Reward(address indexed _address, uint256 value, uint256 _outstandingQuarters, uint256 _totalSupply);
/**
* developer modifier
*/
modifier onlyActiveDeveloper() {
require(developers[msg.sender] == true);
_;
}
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the owner of the contract
*/
function Quarters(
address _q2,
uint256 firstTranche
) public {
q2 = _q2;
tranche = firstTranche; // number of Quarters to be sold before increasing price
}
function setEthRate (uint16 rate) onlyOwner public {
// Ether price is set in Wei
require(rate > 0);
ethRate = rate;
emit EthRateChanged(ethRate, rate);
}
/**
* Adjust reward amount
*/
function adjustReward (uint256 reward) onlyOwner public {
rewardAmount = reward; // may be zero, no need to check value to 0
}
function adjustWithdrawRate(uint32 mega2, uint32 megaRate2, uint32 large2, uint32 largeRate2, uint32 medium2, uint32 mediumRate2, uint32 small2, uint32 smallRate2, uint32 microRate2) onlyOwner public {
// the values (mega, large, medium, small) are multiples, e.g., 20x, 100x, 10000x
// the rates (megaRate, etc.) are percentage points, e.g., 150 is 150% of the remaining etherPool
if (mega2 > 0 && megaRate2 > 0) {
mega = mega2;
megaRate = megaRate2;
}
if (large2 > 0 && largeRate2 > 0) {
large = large2;
largeRate = largeRate2;
}
if (medium2 > 0 && mediumRate2 > 0) {
medium = medium2;
mediumRate = mediumRate2;
}
if (small2 > 0 && smallRate2 > 0){
small = small2;
smallRate = smallRate2;
}
if (microRate2 > 0) {
microRate = microRate2;
}
}
/**
* adjust tranche for next cycle
*/
function adjustNextTranche (uint8 numerator, uint8 denominator) onlyOwner public {
require(numerator > 0 && denominator > 0);
trancheNumerator = numerator;
trancheDenominator = denominator;
}
function adjustTranche(uint256 tranche2) onlyOwner public {
require(tranche2 > 0);
tranche = tranche2;
}
/**
* Adjust rewards for `_address`
*/
function updatePlayerRewards(address _address) internal {
require(_address != address(0));
uint256 _reward = 0;
if (rewards[_address] == 0) {
_reward = rewardAmount;
} else if (rewards[_address] < tranche) {
_reward = trueBuy[_address] * rewardNumerator / rewardDenominator;
}
if (_reward > 0) {
// update rewards record
rewards[_address] = tranche;
balances[_address] += _reward;
allowed[_address][msg.sender] += _reward; // set allowance
totalSupply += _reward;
outstandingQuarters += _reward;
uint256 spentETH = (_reward * (10 ** 18)) / ethRate;
if (reserveETH >= spentETH) {
reserveETH -= spentETH;
} else {
reserveETH = 0;
}
// tranche size change
_changeTrancheIfNeeded();
emit Approval(_address, msg.sender, _reward);
emit Reward(_address, _reward, outstandingQuarters, totalSupply);
}
}
/**
* Developer status
*/
function setDeveloperStatus (address _address, bool status) onlyOwner public {
developers[_address] = status;
emit DeveloperStatusChanged(_address, status);
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
return false;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
outstandingQuarters -= _value; // Update outstanding quarters
emit Burn(msg.sender, _value);
// log rate change
emit BaseRateChanged(getBaseRate(), tranche, outstandingQuarters, address(this).balance, totalSupply);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowed[_from][msg.sender]); // Check allowance
balances[_from] -= _value; // Subtract from the targeted balance
allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
outstandingQuarters -= _value; // Update outstanding quarters
emit Burn(_from, _value);
// log rate change
emit BaseRateChanged(getBaseRate(), tranche, outstandingQuarters, address(this).balance, totalSupply);
return true;
}
/**
* Buy quarters by sending ethers to contract address (no data required)
*/
function () payable public {
_buy(msg.sender);
}
function buy() payable public {
_buy(msg.sender);
}
function buyFor(address buyer) payable public {
uint256 _value = _buy(buyer);
// allow donor (msg.sender) to spend buyer's tokens
allowed[buyer][msg.sender] += _value;
emit Approval(buyer, msg.sender, _value);
}
function _changeTrancheIfNeeded() internal {
if (totalSupply >= tranche) {
// change tranche size for next cycle
tranche = (tranche * trancheNumerator) / trancheDenominator;
// fire event for tranche change
emit TrancheIncreased(tranche, address(this).balance, outstandingQuarters);
}
}
// returns number of quarters buyer got
function _buy(address buyer) internal returns (uint256) {
require(buyer != address(0));
uint256 nq = (msg.value * ethRate) / (10 ** 18);
require(nq != 0);
if (nq > tranche) {
nq = tranche;
}
totalSupply += nq;
balances[buyer] += nq;
trueBuy[buyer] += nq;
outstandingQuarters += nq;
// change tranche size
_changeTrancheIfNeeded();
// event for quarters order (invoice)
emit QuartersOrdered(buyer, msg.value, nq);
// log rate change
emit BaseRateChanged(getBaseRate(), tranche, outstandingQuarters, address(this).balance, totalSupply);
// transfer owner's cut
Q2(q2).disburse.value(msg.value * 15 / 100)();
// return nq
return nq;
}
/**
* Transfer allowance from other address's allowance
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferAllowance(address _from, address _to, uint256 _value) public returns (bool success) {
updatePlayerRewards(_from);
require(_value <= allowed[_from][msg.sender]); // Check allowance
allowed[_from][msg.sender] -= _value;
if (_transfer(_from, _to, _value)) {
// allow msg.sender to spend _to's tokens
allowed[_to][msg.sender] += _value;
emit Approval(_to, msg.sender, _value);
return true;
}
return false;
}
function withdraw(uint256 value) onlyActiveDeveloper public {
require(balances[msg.sender] >= value);
uint256 baseRate = getBaseRate();
require(baseRate > 0); // check if base rate > 0
uint256 earnings = value * baseRate;
uint256 rate = getRate(value); // get rate from value and tranche
uint256 earningsWithBonus = (rate * earnings) / 100;
if (earningsWithBonus > address(this).balance) {
earnings = address(this).balance;
} else {
earnings = earningsWithBonus;
}
balances[msg.sender] -= value;
outstandingQuarters -= value; // update the outstanding Quarters
uint256 etherPool = address(this).balance - earnings;
if (rate == megaRate) {
emit MegaEarnings(msg.sender, earnings, baseRate, tranche, outstandingQuarters, etherPool); // with current base rate
}
// event for withdraw
emit Withdraw(msg.sender, earnings, baseRate, tranche, outstandingQuarters, etherPool); // with current base rate
// log rate change
emit BaseRateChanged(getBaseRate(), tranche, outstandingQuarters, address(this).balance, totalSupply);
// earning for developers
msg.sender.transfer(earnings);
}
function disburse() public payable {
reserveETH += msg.value;
}
function getBaseRate () view public returns (uint256) {
if (outstandingQuarters > 0) {
return (address(this).balance - reserveETH) / outstandingQuarters;
}
return (address(this).balance - reserveETH);
}
function getRate (uint256 value) view public returns (uint32) {
if (value * mega > tranche) { // size & rate for mega developer
return megaRate;
} else if (value * large > tranche) { // size & rate for large developer
return largeRate;
} else if (value * medium > tranche) { // size and rate for medium developer
return mediumRate;
} else if (value * small > tranche){ // size and rate for small developer
return smallRate;
}
return microRate; // rate for micro developer
}
//
// Migrations
//
// Target contract
address public migrationTarget;
bool public migrating = false;
// Migrate event
event Migrate(address indexed _from, uint256 _value);
//
// Migrate tokens to the new token contract.
//
function migrate() public {
require(migrationTarget != address(0));
uint256 _amount = balances[msg.sender];
require(_amount > 0);
balances[msg.sender] = 0;
totalSupply = totalSupply - _amount;
outstandingQuarters = outstandingQuarters - _amount;
rewards[msg.sender] = 0;
trueBuy[msg.sender] = 0;
developers[msg.sender] = false;
emit Migrate(msg.sender, _amount);
MigrationTarget(migrationTarget).migrateFrom(msg.sender, _amount, rewards[msg.sender], trueBuy[msg.sender], developers[msg.sender]);
}
//
// Set address of migration target contract
// @param _target The address of the MigrationTarget contract
//
function setMigrationTarget(address _target) onlyOwner public {
migrationTarget = _target;
}
} | Get Royalty amount for given account account The address for Royalty account/ | function RoyaltysOwing(address account) public view returns (uint256) {
uint256 newRoyalty = totalRoyalty.sub(accounts[account].lastRoyaltyPoint);
return balances[account].mul(newRoyalty).div(totalSupply);
}
| 5,510,555 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
// File: @openzeppelin/contracts/utils/Context.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 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;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <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/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
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);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <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] = 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));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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)))
);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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);
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.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 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;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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;
/*
* 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"
);
return _tokenURIs[tokenId];
}
/**
* @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 Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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,
string memory uri
) internal virtual {
_safeMint(to, tokenId, uri, "");
}
/**
* @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,
string memory uri,
bytes memory _data
) internal virtual {
_mint(to, tokenId, uri);
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,
string memory uri
) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_tokenURIs[tokenId] = uri;
_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
_beforeTokenTransfer(owner, address(0), tokenId);
// 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");
_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 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 Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <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() {
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;
}
}
// File: contracts/Zing.sol
// ____ _ _
// |_ / (_) _ _ __ _ | |
// / / | | | ' \ / _` | |_|
// /___| |_| |_||_| \__, | (_)
// |___/
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.0;
/**
* @title Zing contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract Zing is ERC721, ReentrancyGuard, Ownable {
using SafeMath for uint256;
using Address for address;
string private _contractURI;
uint256 private _tokenIdCounter;
constructor() ERC721("Zing", "ZING") {}
// Set Contract-level URI
function setContractURI(string memory contractURI_) external onlyOwner {
_contractURI = contractURI_;
}
// View Contract-level URI
function contractURI() public view returns (string memory) {
return _contractURI;
}
function mintZing(string calldata uri) public nonReentrant {
_safeMint(msg.sender, _getTokenIdToBeMinted(), uri);
}
function batchMintZing(string[] calldata tokenURIs) public nonReentrant {
address minter = msg.sender;
uint256 len = tokenURIs.length;
for (uint256 i = 0; i < len; ++i) {
_safeMint(minter, _getTokenIdToBeMinted(), tokenURIs[i]);
}
}
function _getTokenIdToBeMinted() private returns (uint256 tokenId) {
tokenId = _tokenIdCounter;
_tokenIdCounter = tokenId.add(1);
}
} | Removes a value from a set. O(1). Returns true if the value was removed from the set, that is if it was present./ We read and store the value's index to prevent multiple reads from the same storage slot 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}. 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. Move the last value to the index where the value to delete is Update the index for the moved value All indexes are 1-based Delete the slot where the moved value was stored Delete the index for the deleted slot | function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = toDeleteIndex + 1;
set._values.pop();
delete set._indexes[value];
return true;
return false;
}
}
| 117,216 |
pragma solidity ^0.4.21;
/******************************************************************************\
*..................................SU.SQUARES..................................*
*.......................Blockchain.rentable.advertising........................*
*..............................................................................*
* First, I just want to say we are so excited and humbled to get this far and *
* that you're even reading this. So thank you! *
* *
* This file is organized into multiple contracts that separate functionality *
* into logical parts. The deployed contract, SuMain, is at the bottom and *
* includes the rest of the file using inheritance. *
* *
* - ERC165, ERC721: These interfaces follow the official EIPs *
* - AccessControl: A reusable CEO/CFO/COO access model *
* - PublishInterfaces: An implementation of ERC165 *
* - SuNFT: An implementation of ERC721 *
* - SuOperation: The actual square data and the personalize function *
* - SuPromo, SuVending: How we sell or grant squares *
*..............................................................................*
*............................Su.&.William.Entriken.............................*
*...................................(c) 2018...................................*
\******************************************************************************/
/* AccessControl.sol **********************************************************/
/// @title Reusable three-role access control inspired by CryptoKitties
/// @author William Entriken (https://phor.net)
/// @dev Keep the CEO wallet stored offline, I warned you
contract AccessControl {
/// @notice The account that can only reassign executive accounts
address public executiveOfficerAddress;
/// @notice The account that can collect funds from this contract
address public financialOfficerAddress;
/// @notice The account with administrative control of this contract
address public operatingOfficerAddress;
function AccessControl() internal {
executiveOfficerAddress = msg.sender;
}
/// @dev Only allowed by executive officer
modifier onlyExecutiveOfficer() {
require(msg.sender == executiveOfficerAddress);
_;
}
/// @dev Only allowed by financial officer
modifier onlyFinancialOfficer() {
require(msg.sender == financialOfficerAddress);
_;
}
/// @dev Only allowed by operating officer
modifier onlyOperatingOfficer() {
require(msg.sender == operatingOfficerAddress);
_;
}
/// @notice Reassign the executive officer role
/// @param _executiveOfficerAddress new officer address
function setExecutiveOfficer(address _executiveOfficerAddress)
external
onlyExecutiveOfficer
{
require(_executiveOfficerAddress != address(0));
executiveOfficerAddress = _executiveOfficerAddress;
}
/// @notice Reassign the financial officer role
/// @param _financialOfficerAddress new officer address
function setFinancialOfficer(address _financialOfficerAddress)
external
onlyExecutiveOfficer
{
require(_financialOfficerAddress != address(0));
financialOfficerAddress = _financialOfficerAddress;
}
/// @notice Reassign the operating officer role
/// @param _operatingOfficerAddress new officer address
function setOperatingOfficer(address _operatingOfficerAddress)
external
onlyExecutiveOfficer
{
require(_operatingOfficerAddress != address(0));
operatingOfficerAddress = _operatingOfficerAddress;
}
/// @notice Collect funds from this contract
function withdrawBalance() external onlyFinancialOfficer {
financialOfficerAddress.transfer(address(this).balance);
}
}
/* ERC165.sol *****************************************************************/
/// @title ERC-165 Standard Interface Detection
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/* ERC721.sol *****************************************************************/
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
contract ERC721 is ERC165 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard
interface ERC721TokenReceiver {
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
interface ERC721Metadata /* is ERC721 */ {
function name() external pure returns (string _name);
function symbol() external pure returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
interface ERC721Enumerable /* is ERC721 */ {
function totalSupply() external view returns (uint256);
function tokenByIndex(uint256 _index) external view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/* PublishInterfaces.sol ******************************************************/
/// @title A reusable contract to comply with ERC-165
/// @author William Entriken (https://phor.net)
contract PublishInterfaces is ERC165 {
/// @dev Every interface that we support
mapping(bytes4 => bool) internal supportedInterfaces;
function PublishInterfaces() internal {
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return supportedInterfaces[interfaceID] && (interfaceID != 0xffffffff);
}
}
/* SuNFT.sol ******************************************************************/
/// @title Compliance with ERC-721 for Su Squares
/// @dev This implementation assumes:
/// - A fixed supply of NFTs, cannot mint or burn
/// - ids are numbered sequentially starting at 1.
/// - NFTs are initially assigned to this contract
/// - This contract does not externally call its own functions
/// @author William Entriken (https://phor.net)
contract SuNFT is ERC165, ERC721, ERC721Metadata, ERC721Enumerable, PublishInterfaces {
/// @dev The authorized address for each NFT
mapping (uint256 => address) internal tokenApprovals;
/// @dev The authorized operators for each address
mapping (address => mapping (address => bool)) internal operatorApprovals;
/// @dev Guarantees msg.sender is the owner of _tokenId
/// @param _tokenId The token to validate belongs to msg.sender
modifier onlyOwnerOf(uint256 _tokenId) {
address owner = _tokenOwnerWithSubstitutions[_tokenId];
// assert(msg.sender != address(this))
require(msg.sender == owner);
_;
}
modifier mustBeOwnedByThisContract(uint256 _tokenId) {
require(_tokenId >= 1 && _tokenId <= TOTAL_SUPPLY);
address owner = _tokenOwnerWithSubstitutions[_tokenId];
require(owner == address(0) || owner == address(this));
_;
}
modifier canOperate(uint256 _tokenId) {
// assert(msg.sender != address(this))
address owner = _tokenOwnerWithSubstitutions[_tokenId];
require(msg.sender == owner || operatorApprovals[owner][msg.sender]);
_;
}
modifier canTransfer(uint256 _tokenId) {
// assert(msg.sender != address(this))
address owner = _tokenOwnerWithSubstitutions[_tokenId];
require(msg.sender == owner ||
msg.sender == tokenApprovals[_tokenId] ||
operatorApprovals[msg.sender][msg.sender]);
_;
}
modifier mustBeValidToken(uint256 _tokenId) {
require(_tokenId >= 1 && _tokenId <= TOTAL_SUPPLY);
_;
}
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256) {
require(_owner != address(0));
return _tokensOfOwnerWithSubstitutions[_owner].length;
}
/// @notice Find the owner of an NFT
/// @param _tokenId The identifier for an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId)
external
view
mustBeValidToken(_tokenId)
returns (address _owner)
{
_owner = _tokenOwnerWithSubstitutions[_tokenId];
// Handle substitutions
if (_owner == address(0)) {
_owner = address(this);
}
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable
{
_safeTransferFrom(_from, _to, _tokenId, data);
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to ""
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId)
external
payable
mustBeValidToken(_tokenId)
canTransfer(_tokenId)
{
address owner = _tokenOwnerWithSubstitutions[_tokenId];
// Handle substitutions
if (owner == address(0)) {
owner = address(this);
}
require(owner == _from);
require(_to != address(0));
_transfer(_tokenId, _to);
}
/// @notice Set or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId)
external
payable
// assert(mustBeValidToken(_tokenId))
canOperate(_tokenId)
{
address _owner = _tokenOwnerWithSubstitutions[_tokenId];
// Handle substitutions
if (_owner == address(0)) {
_owner = address(this);
}
tokenApprovals[_tokenId] = _approved;
emit Approval(_owner, _approved, _tokenId);
}
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all your asset.
/// @dev Emits the ApprovalForAll event
/// @param _operator Address to add to the set of authorized operators.
/// @param _approved True if the operators is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external {
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId)
external
view
mustBeValidToken(_tokenId)
returns (address)
{
return tokenApprovals[_tokenId];
}
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorApprovals[_owner][_operator];
}
// COMPLIANCE WITH ERC721Metadata //////////////////////////////////////////
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure returns (string) {
return "Su Squares";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure returns (string) {
return "SU";
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId)
external
view
mustBeValidToken(_tokenId)
returns (string _tokenURI)
{
_tokenURI = "https://tenthousandsu.com/erc721/00000.json";
bytes memory _tokenURIBytes = bytes(_tokenURI);
_tokenURIBytes[33] = byte(48+(_tokenId / 10000) % 10);
_tokenURIBytes[34] = byte(48+(_tokenId / 1000) % 10);
_tokenURIBytes[35] = byte(48+(_tokenId / 100) % 10);
_tokenURIBytes[36] = byte(48+(_tokenId / 10) % 10);
_tokenURIBytes[37] = byte(48+(_tokenId / 1) % 10);
}
// COMPLIANCE WITH ERC721Enumerable ////////////////////////////////////////
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256) {
return TOTAL_SUPPLY;
}
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < TOTAL_SUPPLY);
return _index + 1;
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) {
require(_owner != address(0));
require(_index < _tokensOfOwnerWithSubstitutions[_owner].length);
_tokenId = _tokensOfOwnerWithSubstitutions[_owner][_index];
// Handle substitutions
if (_owner == address(this)) {
if (_tokenId == 0) {
_tokenId = _index + 1;
}
}
}
// INTERNAL INTERFACE //////////////////////////////////////////////////////
/// @dev Actually do a transfer, does NO precondition checking
function _transfer(uint256 _tokenId, address _to) internal {
// Here are the preconditions we are not checking:
// assert(canTransfer(_tokenId))
// assert(mustBeValidToken(_tokenId))
require(_to != address(0));
// Find the FROM address
address fromWithSubstitution = _tokenOwnerWithSubstitutions[_tokenId];
address from = fromWithSubstitution;
if (fromWithSubstitution == address(0)) {
from = address(this);
}
// Take away from the FROM address
// The Entriken algorithm for deleting from an indexed, unsorted array
uint256 indexToDeleteWithSubstitution = _ownedTokensIndexWithSubstitutions[_tokenId];
uint256 indexToDelete;
if (indexToDeleteWithSubstitution == 0) {
indexToDelete = _tokenId - 1;
} else {
indexToDelete = indexToDeleteWithSubstitution - 1;
}
if (indexToDelete != _tokensOfOwnerWithSubstitutions[from].length - 1) {
uint256 lastNftWithSubstitution = _tokensOfOwnerWithSubstitutions[from][_tokensOfOwnerWithSubstitutions[from].length - 1];
uint256 lastNft = lastNftWithSubstitution;
if (lastNftWithSubstitution == 0) {
// assert(from == address(0) || from == address(this));
lastNft = _tokensOfOwnerWithSubstitutions[from].length;
}
_tokensOfOwnerWithSubstitutions[from][indexToDelete] = lastNft;
_ownedTokensIndexWithSubstitutions[lastNft] = indexToDelete + 1;
}
delete _tokensOfOwnerWithSubstitutions[from][_tokensOfOwnerWithSubstitutions[from].length - 1]; // get gas back
_tokensOfOwnerWithSubstitutions[from].length--;
// Right now _ownedTokensIndexWithSubstitutions[_tokenId] is invalid, set it below based on the new owner
// Give to the TO address
_tokensOfOwnerWithSubstitutions[_to].push(_tokenId);
_ownedTokensIndexWithSubstitutions[_tokenId] = (_tokensOfOwnerWithSubstitutions[_to].length - 1) + 1;
// External processing
_tokenOwnerWithSubstitutions[_tokenId] = _to;
tokenApprovals[_tokenId] = address(0);
emit Transfer(from, _to, _tokenId);
}
// PRIVATE STORAGE AND FUNCTIONS ///////////////////////////////////////////
uint256 private constant TOTAL_SUPPLY = 10000; // SOLIDITY ISSUE #3356 make this immutable
bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
/// @dev The owner of each NFT
/// If value == address(0), NFT is owned by address(this)
/// If value != address(0), NFT is owned by value
/// assert(This contract never assigns awnerhip to address(0) or destroys NFTs)
/// See commented out code in constructor, saves hella gas
mapping (uint256 => address) private _tokenOwnerWithSubstitutions;
/// @dev The list of NFTs owned by each address
/// Nomenclature: this[key][index] = value
/// If key != address(this) or value != 0, then value represents an NFT
/// If key == address(this) and value == 0, then index + 1 is the NFT
/// assert(0 is not a valid NFT)
/// See commented out code in constructor, saves hella gas
mapping (address => uint256[]) private _tokensOfOwnerWithSubstitutions;
/// @dev (Location + 1) of each NFT in its owner's list
/// Nomenclature: this[key] = value
/// If value != 0, _tokensOfOwnerWithSubstitutions[owner][value - 1] = nftId
/// If value == 0, _tokensOfOwnerWithSubstitutions[owner][key - 1] = nftId
/// assert(2**256-1 is not a valid NFT)
/// See commented out code in constructor, saves hella gas
mapping (uint256 => uint256) private _ownedTokensIndexWithSubstitutions;
// Due to implementation choices (no mint, no burn, contiguous NFT ids), it
// is not necessary to keep an array of NFT ids nor where each NFT id is
// located in that array.
// address[] private nftIds;
// mapping (uint256 => uint256) private nftIndexOfId;
function SuNFT() internal {
// Publish interfaces with ERC-165
supportedInterfaces[0x6466353c] = true; // ERC721
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
// The effect of substitution makes storing address(this), address(this)
// ..., address(this) for a total of TOTAL_SUPPLY times unnecessary at
// deployment time
// for (uint256 i = 1; i <= TOTAL_SUPPLY; i++) {
// _tokenOwnerWithSubstitutions[i] = address(this);
// }
// The effect of substitution makes storing 1, 2, ..., TOTAL_SUPPLY
// unnecessary at deployment time
_tokensOfOwnerWithSubstitutions[address(this)].length = TOTAL_SUPPLY;
// for (uint256 i = 0; i < TOTAL_SUPPLY; i++) {
// _tokensOfOwnerWithSubstitutions[address(this)][i] = i + 1;
// }
// for (uint256 i = 1; i <= TOTAL_SUPPLY; i++) {
// _ownedTokensIndexWithSubstitutions[i] = i - 1;
// }
}
/// @dev Actually perform the safeTransferFrom
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)
private
mustBeValidToken(_tokenId)
canTransfer(_tokenId)
{
address owner = _tokenOwnerWithSubstitutions[_tokenId];
// Handle substitutions
if (owner == address(0)) {
owner = address(this);
}
require(owner == _from);
require(_to != address(0));
_transfer(_tokenId, _to);
// Do the callback after everything is done to avoid reentrancy attack
uint256 codeSize;
assembly { codeSize := extcodesize(_to) }
if (codeSize == 0) {
return;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
require(retval == ERC721_RECEIVED);
}
}
/* SuOperation.sol ************************************************************/
/// @title The features that square owners can use
/// @author William Entriken (https://phor.net)
/// @dev See SuMain contract documentation for detail on how contracts interact.
contract SuOperation is SuNFT {
/// @dev The personalization of a square has changed
event Personalized(uint256 _nftId);
/// @dev The main SuSquare struct. The owner may set these properties, subject
/// subject to certain rules. The actual 10x10 image is rendered on our
/// website using this data.
struct SuSquare {
/// @dev This increments on each update
uint256 version;
/// @dev A 10x10 pixel image, stored 8-bit RGB values from left-to-right
/// and top-to-bottom order (normal English reading order). So it is
/// exactly 300 bytes. Or it is an empty array.
/// So the first byte is the red channel for the top-left pixel, then
/// the blue, then the green, and then next is the red channel for the
/// pixel to the right of the first pixel.
bytes rgbData;
/// @dev The title of this square, at most 64 bytes,
string title;
/// @dev The URL of this square, at most 100 bytes, or empty string
string href;
}
/// @notice All the Su Squares that ever exist or will exist. Each Su Square
/// represents a square on our webpage in a 100x100 grid. The squares are
/// arranged in left-to-right, top-to-bottom order. In other words, normal
/// English reading order. So suSquares[1] is the top-left location and
/// suSquares[100] is the top-right location. And suSquares[101] is
/// directly below suSquares[1].
/// @dev There is no suSquares[0] -- that is an unused array index.
SuSquare[10001] public suSquares;
/// @notice Update the contents of your square, the first 3 personalizations
/// for a square are free then cost 100 finney (0.1 ether) each
/// @param _squareId The top-left is 1, to its right is 2, ..., top-right is
/// 100 and then 101 is below 1... the last one at bottom-right is 10000
/// @param _squareId A 10x10 image for your square, in 8-bit RGB words
/// ordered like the squares are ordered. See Imagemagick's command
/// convert -size 10x10 -depth 8 in.rgb out.png
/// @param _title A description of your square (max 64 bytes UTF-8)
/// @param _href A hyperlink for your square (max 96 bytes)
function personalizeSquare(
uint256 _squareId,
bytes _rgbData,
string _title,
string _href
)
external
onlyOwnerOf(_squareId)
payable
{
require(bytes(_title).length <= 64);
require(bytes(_href).length <= 96);
require(_rgbData.length == 300);
suSquares[_squareId].version++;
suSquares[_squareId].rgbData = _rgbData;
suSquares[_squareId].title = _title;
suSquares[_squareId].href = _href;
if (suSquares[_squareId].version > 3) {
require(msg.value == 100 finney);
}
emit Personalized(_squareId);
}
}
/* SuPromo.sol ****************************************************************/
/// @title A limited pre-sale and promotional giveaway.
/// @author William Entriken (https://phor.net)
/// @dev See SuMain contract documentation for detail on how contracts interact.
contract SuPromo is AccessControl, SuNFT {
uint256 constant PROMO_CREATION_LIMIT = 5000;
/// @notice How many promo squares were granted
uint256 public promoCreatedCount;
/// @notice BEWARE, this does not use a safe transfer mechanism!
/// You must manually check the receiver can accept NFTs
function grantToken(uint256 _tokenId, address _newOwner)
external
onlyOperatingOfficer
mustBeValidToken(_tokenId)
mustBeOwnedByThisContract(_tokenId)
{
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_transfer(_tokenId, _newOwner);
}
}
/* SuVending.sol **************************************************************/
/// @title A token vending machine
/// @author William Entriken (https://phor.net)
/// @dev See SuMain contract documentation for detail on how contracts interact.
contract SuVending is SuNFT {
uint256 constant SALE_PRICE = 500 finney; // 0.5 ether
/// @notice The price is always 0.5 ether, and you can buy any available square
/// Be sure you are calling this from a regular account (not a smart contract)
/// or if you are calling from a smart contract, make sure it can use
/// ERC-721 non-fungible tokens
function purchase(uint256 _nftId)
external
payable
mustBeValidToken(_nftId)
mustBeOwnedByThisContract(_nftId)
{
require(msg.value == SALE_PRICE);
_transfer(_nftId, msg.sender);
}
}
/* SuMain.sol *****************************************************************/
/// @title The features that deed owners can use
/// @author William Entriken (https://phor.net)
/// @dev See SuMain contract documentation for detail on how contracts interact.
contract SuMain is AccessControl, SuNFT, SuOperation, SuVending, SuPromo {
function SuMain() public {
}
} | Actually perform the safeTransferFrom Handle substitutions | function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)
private
mustBeValidToken(_tokenId)
canTransfer(_tokenId)
{
address owner = _tokenOwnerWithSubstitutions[_tokenId];
if (owner == address(0)) {
owner = address(this);
}
require(owner == _from);
require(_to != address(0));
_transfer(_tokenId, _to);
if (codeSize == 0) {
return;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
require(retval == ERC721_RECEIVED);
}
| 10,856,415 |
./partial_match/1285/0x09244059E82cc544F19c9Ee3A3a87093a2867ea5/sources/contracts/wenGame/DPSGameSettings.sol | computes skills for the flagship based on the level of the part of the flagship + base skills of the flagship levels levels for each part, needs to respect the order of the levels from flagship _claimingRewardsCache the cache object that contains the skill points per skill type return cached object with the skill points updated/ | function computeFlagShipSkills(uint8[7] calldata levels, VoyageStatusCache memory _claimingRewardsCache)
external
view
returns (VoyageStatusCache memory)
{
unchecked {
uint16[7] memory skillsPerPart = getSkillsPerFlagshipParts();
uint8[7] memory skillTypes = getSkillTypeOfEachFlagshipPart();
_claimingRewardsCache.luck += flagshipBaseSkills;
_claimingRewardsCache.navigation += flagshipBaseSkills;
_claimingRewardsCache.strength += flagshipBaseSkills;
for (uint256 i; i < 7; i++) {
if (skillTypes[i] == uint8(SKILL_TYPE.LUCK)) _claimingRewardsCache.luck += skillsPerPart[i] * levels[i];
if (skillTypes[i] == uint8(SKILL_TYPE.NAVIGATION))
_claimingRewardsCache.navigation += skillsPerPart[i] * levels[i];
if (skillTypes[i] == uint8(SKILL_TYPE.STRENGTH))
_claimingRewardsCache.strength += skillsPerPart[i] * levels[i];
}
return _claimingRewardsCache;
}
}
| 8,794,942 |
//Autor: Prof. Fabio Santos ([email protected])
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
//importação da classe Ownable da biblioteca openzeppelin.
import "@openzeppelin/contracts/access/Ownable.sol";
//Estendendo a Ownable permite adicionar o modificador onlyOwner às nossas funções para que apenas o proprietário do contrato
//possa executá-las
contract TimeLockFunctions is Ownable {
//O enum nos permite acessar a função de time-locked de forma mais legível
enum Functions { ADI, SUB, MUL, DIV }
//_TIMELOCK constante define o quanto queremos que nossas funções esperem até que possam ser executadas
uint256 private constant _TIMELOCK = 0 days;
//um mapeamento de time-locked que nos ajuda a ver qual função está atualmente desbloqueada
mapping(Functions => uint256) public timelock;
//modificador que verifica se uma função está desbloqueada
//Verificando se o atual horário é maior do que quando ativamos o desbloqueio
modifier notLocked(Functions _fn) {
require(timelock[_fn] != 0 && timelock[_fn] <= block.timestamp, "Funcao esta bloqueada(time-locked)");
_;
}
//função de desbloqueio que nos permite chamar nossas funções após a quantidade de dias definido na constante _TIMELOCK
function unlockFunction(Functions _fn) public onlyOwner {
timelock[_fn] = block.timestamp + _TIMELOCK;
}
//função de bloqueio caso queiramos cancelar o tempo
function lockFunction(Functions _fn) public onlyOwner {
timelock[_fn] = 0;
}
//Finalmente, verificamos se as funções estão desbloqueadas e as bloqueamos de volta depois de usá-las
function adicao(uint a, uint b) view public onlyOwner notLocked(Functions.ADI) returns (uint) {
return a + b;
}
function subtracao(uint a, uint b) view public onlyOwner notLocked(Functions.SUB) returns (uint) {
return a - b;
}
function multiplicacao(uint a, uint b) view public onlyOwner notLocked(Functions.MUL) returns (uint){
return a * b;
}
function divisao(uint a, uint b) view public onlyOwner notLocked(Functions.DIV) returns (uint) {
uint result;
if (b != 0){
result = a / b;
}
return result;
}
} | função de desbloqueio que nos permite chamar nossas funções após a quantidade de dias definido na constante _TIMELOCK | function unlockFunction(Functions _fn) public onlyOwner {
timelock[_fn] = block.timestamp + _TIMELOCK;
}
| 5,491,060 |
./partial_match/1/0xDD3A8f6793AFBFA8d7C8e2B19106175DcCabEc41/sources/ELCK.sol | PUBLIC FACING: External helper to return multiple values of daily data with a single call. beginDay First day of data range endDay Last day (non-inclusive) of data range return array of day stake shares total return array of day payout total/ | function dailyDataRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory _dayStakeSharesTotal, uint256[] memory _dayPayoutTotal, uint256[] memory _dayDividends)
{
require(beginDay < endDay && endDay <= globals.dailyDataCount, "ELCK: range invalid");
_dayStakeSharesTotal = new uint256[](endDay - beginDay);
_dayPayoutTotal = new uint256[](endDay - beginDay);
_dayDividends = new uint256[](endDay - beginDay);
uint256 src = beginDay;
uint256 dst = 0;
do {
_dayStakeSharesTotal[dst] = uint256(dailyData[src].dayStakeSharesTotal);
_dayPayoutTotal[dst++] = uint256(dailyData[src].dayPayoutTotal);
_dayDividends[dst++] = dailyData[src].dayDividends;
} while (++src < endDay);
return (_dayStakeSharesTotal, _dayPayoutTotal, _dayDividends);
}
| 4,031,253 |
./partial_match/3/0xd8737266A2Ce560a79643Ee84407a94b0F2D5E7c/sources/PairToken.sol | send `value` token to `to` from `from` on the condition it is approved by `from` from The address of the sender to The address of the recipient value The amount of token to be transferred return Whether the transfer was successful or not | function transferFrom(address from, address to, uint256 value) public returns (bool success) {}
| 5,238,709 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.10;
import "./types/NoteKeeper.sol";
import "./libraries/SafeERC20.sol";
import "./interfaces/IERC20Metadata.sol";
import "./interfaces/IBondDepository.sol";
/// @title Floor Bond Depository V2
/// @author Zeus, Indigo
/// Review by: JeffX
contract FloorBondDepository is IBondDepository, NoteKeeper {
/* ======== DEPENDENCIES ======== */
using SafeERC20 for IERC20;
/* ======== EVENTS ======== */
event CreateMarket(
uint256 indexed id,
address indexed quoteToken,
uint256 initialPrice,
uint256 capacity,
bool capacityInQuote,
uint256 conclusion,
uint256 vestingPeriod
);
event CloseMarket(uint256 indexed id);
event Tuned(uint256 indexed id, uint64 oldControlVariable, uint64 newControlVariable);
event Bond(uint256 indexed id, uint256 amount, uint256 price, uint256 payout);
/* ======== STATE VARIABLES ======== */
// Storage
Market[] public markets; // persistent market data
Terms[] public terms; // deposit construction data
Metadata[] public metadata; // extraneous market data
mapping(uint256 => Adjustment) public adjustments; // control variable changes
// Queries
mapping(address => uint256[]) public marketsForQuote; // market IDs for quote token
/* ======== CONSTRUCTOR ======== */
constructor(
IFloorAuthority _authority,
IERC20 _floor,
IgFLOOR _gfloor,
IStaking _staking,
ITreasury _treasury
) NoteKeeper(_authority, _floor, _gfloor, _staking, _treasury) {
// save gas for users by bulk approving stake() transactions
_floor.approve(address(_staking), 1e45);
}
/* ======== DEPOSIT ======== */
/**
* @notice deposit quote tokens in exchange for a bond from a specified market
* @param _id the ID of the market
* @param _amount the amount of quote token to spend
* @param _maxPrice the maximum price at which to buy
* @param _user the recipient of the payout
* @param _referral the front end operator address
* @return payout_ the amount of gFLOOR due
* @return expiry_ the timestamp at which payout is redeemable
* @return index_ the user index of the Note (used to redeem or query information)
*/
function deposit(
uint256 _id,
uint256 _amount,
uint256 _maxPrice,
address _user,
address _referral
) external override returns (
uint256 payout_,
uint256 expiry_,
uint256 index_
) {
Market storage market = markets[_id];
Terms memory term = terms[_id];
uint48 currentTime = uint48(block.timestamp);
// Markets end at a defined timestamp
// |-------------------------------------| t
require(currentTime < term.conclusion, "Depository: market concluded");
// Debt and the control variable decay over time
_decay(_id, currentTime);
// Users input a maximum price, which protects them from price changes after
// entering the mempool. max price is a slippage mitigation measure
uint256 price = _marketPrice(_id);
require(price <= _maxPrice, "Depository: more than max price");
/**
* payout for the deposit = amount / price
*
* where
* payout = FLOOR out
* amount = quote tokens in
* price = quote tokens : floor (i.e. 42069 DAI : FLOOR)
*
* 1e18 = FLOOR decimals (9) + price decimals (9)
*/
payout_ = (_amount * 1e18 / price) / (10 ** metadata[_id].quoteDecimals);
// markets have a max payout amount, capping size because deposits
// do not experience slippage. max payout is recalculated upon tuning
require(payout_ <= market.maxPayout, "Depository: max size exceeded");
/*
* each market is initialized with a capacity
*
* this is either the number of FLOOR that the market can sell
* (if capacity in quote is false),
*
* or the number of quote tokens that the market can buy
* (if capacity in quote is true)
*/
market.capacity -= market.capacityInQuote
? _amount
: payout_;
/**
* bonds mature with a cliff at a set timestamp
* prior to the expiry timestamp, no payout tokens are accessible to the user
* after the expiry timestamp, the entire payout can be redeemed
*
* there are two types of bonds: fixed-term and fixed-expiration
*
* fixed-term bonds mature in a set amount of time from deposit
* i.e. term = 1 week. when alice deposits on day 1, her bond
* expires on day 8. when bob deposits on day 2, his bond expires day 9.
*
* fixed-expiration bonds mature at a set timestamp
* i.e. expiration = day 10. when alice deposits on day 1, her term
* is 9 days. when bob deposits on day 2, his term is 8 days.
*/
expiry_ = term.fixedTerm
? term.vesting + currentTime
: term.vesting;
// markets keep track of how many quote tokens have been
// purchased, and how much FLOOR has been sold
market.purchased += _amount;
market.sold += uint64(payout_);
// incrementing total debt raises the price of the next bond
market.totalDebt += uint64(payout_);
emit Bond(_id, _amount, price, payout_);
/**
* user data is stored as Notes. these are isolated array entries
* storing the amount due, the time created, the time when payout
* is redeemable, the time when payout was redeemed, and the ID
* of the market deposited into
*/
index_ = addNote(
_user,
payout_,
uint48(expiry_),
uint48(_id),
_referral
);
// transfer payment to treasury
market.quoteToken.safeTransferFrom(msg.sender, address(treasury), _amount);
// if max debt is breached, the market is closed
// this a circuit breaker
if (term.maxDebt < market.totalDebt) {
market.capacity = 0;
emit CloseMarket(_id);
} else {
// if market will continue, the control variable is tuned to hit targets on time
_tune(_id, currentTime);
}
}
/**
* @notice decay debt, and adjust control variable if there is an active change
* @param _id ID of market
* @param _time uint48 timestamp (saves gas when passed in)
*/
function _decay(uint256 _id, uint48 _time) internal {
// Debt decay
/*
* Debt is a time-decayed sum of tokens spent in a market
* Debt is added when deposits occur and removed over time
* |
* | debt falls with
* | / \ inactivity / \
* | / \ /\/ \
* | \ / \
* | \ /\/ \
* | \ / and rises \
* | with deposits
* |
* |------------------------------------| t
*/
markets[_id].totalDebt -= debtDecay(_id);
metadata[_id].lastDecay = _time;
// Control variable decay
// The bond control variable is continually tuned. When it is lowered (which
// lowers the market price), the change is carried out smoothly over time.
if (adjustments[_id].active) {
Adjustment storage adjustment = adjustments[_id];
(uint64 adjustBy, uint48 secondsSince, bool stillActive) = _controlDecay(_id);
terms[_id].controlVariable -= adjustBy;
if (stillActive) {
adjustment.change -= adjustBy;
adjustment.timeToAdjusted -= secondsSince;
adjustment.lastAdjustment = _time;
} else {
adjustment.active = false;
}
}
}
/**
* @notice auto-adjust control variable to hit capacity/spend target
* @param _id ID of market
* @param _time uint48 timestamp (saves gas when passed in)
*/
function _tune(uint256 _id, uint48 _time) internal {
Metadata memory meta = metadata[_id];
if (_time >= meta.lastTune + meta.tuneInterval) {
Market memory market = markets[_id];
// compute seconds remaining until market will conclude
uint256 timeRemaining = terms[_id].conclusion - _time;
uint256 price = _marketPrice(_id);
// standardize capacity into an base token amount
// floor decimals (9) + price decimals (9)
uint256 capacity = market.capacityInQuote
? (market.capacity * 1e18 / price) / (10 ** meta.quoteDecimals)
: market.capacity;
/**
* calculate the correct payout to complete on time assuming each bond
* will be max size in the desired deposit interval for the remaining time
*
* i.e. market has 10 days remaining. deposit interval is 1 day. capacity
* is 10,000 FLOOR. max payout would be 1,000 FLOOR (10,000 * 1 / 10).
*/
markets[_id].maxPayout = uint64(capacity * meta.depositInterval / timeRemaining);
// calculate the ideal total debt to satisfy capacity in the remaining time
uint256 targetDebt = capacity * meta.length / timeRemaining;
// derive a new control variable from the target debt and current supply
uint64 newControlVariable = uint64(price * treasury.baseSupply() / targetDebt);
emit Tuned(_id, terms[_id].controlVariable, newControlVariable);
if (newControlVariable >= terms[_id].controlVariable) {
terms[_id].controlVariable = newControlVariable;
} else {
// if decrease, control variable change will be carried out over the tune interval
// this is because price will be lowered
uint64 change = terms[_id].controlVariable - newControlVariable;
adjustments[_id] = Adjustment(change, _time, meta.tuneInterval, true);
}
metadata[_id].lastTune = _time;
}
}
/* ======== CREATE ======== */
/**
* @notice creates a new market type
* @dev current price should be in 9 decimals.
* @param _quoteToken token used to deposit
* @param _market [capacity (in FLOOR or quote), initial price / FLOOR (9 decimals), debt buffer (3 decimals)]
* @param _booleans [capacity in quote, fixed term]
* @param _terms [(seconds) vesting length (if fixed term) or vested timestamp, conclusion timestamp]
* @param _intervals [deposit interval (seconds), tune interval (seconds)]
* @return id_ ID of new bond market
*/
function create(
IERC20 _quoteToken,
uint256[3] memory _market,
bool[2] memory _booleans,
uint256[2] memory _terms,
uint32[2] memory _intervals
) external override onlyPolicy returns (uint256 id_) {
// the length of the program, in seconds
uint256 secondsToConclusion = _terms[1] - block.timestamp;
// the decimal count of the quote token
uint256 decimals = IERC20Metadata(address(_quoteToken)).decimals();
/*
* initial target debt is equal to capacity (this is the amount of debt
* that will decay over in the length of the program if price remains the same).
* it is converted into base token terms if passed in in quote token terms.
*
* 1e18 = floor decimals (9) + initial price decimals (9)
*/
uint64 targetDebt = uint64(_booleans[0]
? (_market[0] * 1e18 / _market[1]) / 10 ** decimals
: _market[0]
);
/*
* max payout is the amount of capacity that should be utilized in a deposit
* interval. for example, if capacity is 1,000 FLOOR, there are 10 days to conclusion,
* and the preferred deposit interval is 1 day, max payout would be 100 FLOOR.
*/
uint64 maxPayout = uint64(targetDebt * _intervals[0] / secondsToConclusion);
/*
* max debt serves as a circuit breaker for the market. let's say the quote
* token is a stablecoin, and that stablecoin depegs. without max debt, the
* market would continue to buy until it runs out of capacity. this is
* configurable with a 3 decimal buffer (1000 = 1% above initial price).
* note that its likely advisable to keep this buffer wide.
* note that the buffer is above 100%. i.e. 10% buffer = initial debt * 1.1
*/
uint256 maxDebt = targetDebt + (targetDebt * _market[2] / 1e5); // 1e5 = 100,000. 10,000 / 100,000 = 10%.
/*
* the control variable is set so that initial price equals the desired
* initial price. the control variable is the ultimate determinant of price,
* so we compute this last.
*
* price = control variable * debt ratio
* debt ratio = total debt / supply
* therefore, control variable = price / debt ratio
*/
uint256 controlVariable = _market[1] * treasury.baseSupply() / targetDebt;
// depositing into, or getting info for, the created market uses this ID
id_ = markets.length;
markets.push(Market({
quoteToken: _quoteToken,
capacityInQuote: _booleans[0],
capacity: _market[0],
totalDebt: targetDebt,
maxPayout: maxPayout,
purchased: 0,
sold: 0
}));
terms.push(Terms({
fixedTerm: _booleans[1],
controlVariable: uint64(controlVariable),
vesting: uint48(_terms[0]),
conclusion: uint48(_terms[1]),
maxDebt: uint64(maxDebt)
}));
metadata.push(Metadata({
lastTune: uint48(block.timestamp),
lastDecay: uint48(block.timestamp),
length: uint48(secondsToConclusion),
depositInterval: _intervals[0],
tuneInterval: _intervals[1],
quoteDecimals: uint8(decimals)
}));
marketsForQuote[address(_quoteToken)].push(id_);
emit CreateMarket(id_, address(_quoteToken), _market[1], _market[0], _booleans[0], _terms[1], _terms[0]);
}
/**
* @notice disable existing market
* @param _id ID of market to close
*/
function close(uint256 _id) external override onlyPolicy {
terms[_id].conclusion = uint48(block.timestamp);
markets[_id].capacity = 0;
emit CloseMarket(_id);
}
/* ======== EXTERNAL VIEW ======== */
/**
* @notice calculate current market price of quote token in base token
* @dev accounts for debt and control variable decay since last deposit (vs _marketPrice())
* @param _id ID of market
* @return price for market in FLOOR decimals
*
* price is derived from the equation
*
* p = cv * dr
*
* where
* p = price
* cv = control variable
* dr = debt ratio
*
* dr = d / s
*
* where
* d = debt
* s = supply of token at market creation
*
* d -= ( d * (dt / l) )
*
* where
* dt = change in time
* l = length of program
*/
function marketPrice(uint256 _id) public view override returns (uint256) {
return
currentControlVariable(_id)
* debtRatio(_id)
/ (10 ** metadata[_id].quoteDecimals);
}
/**
* @notice payout due for amount of quote tokens
* @dev accounts for debt and control variable decay so it is up to date
* @param _amount amount of quote tokens to spend
* @param _id ID of market
* @return amount of FLOOR to be paid in FLOOR decimals
*
* @dev 1e18 = floor decimals (9) + market price decimals (9)
*/
function payoutFor(uint256 _amount, uint256 _id) external view override returns (uint256) {
Metadata memory meta = metadata[_id];
return
_amount
* 1e18
/ marketPrice(_id)
/ 10 ** meta.quoteDecimals;
}
/**
* @notice calculate current ratio of debt to supply
* @dev uses current debt, which accounts for debt decay since last deposit (vs _debtRatio())
* @param _id ID of market
* @return debt ratio for market in quote decimals
*/
function debtRatio(uint256 _id) public view override returns (uint256) {
return
currentDebt(_id)
* (10 ** metadata[_id].quoteDecimals)
/ treasury.baseSupply();
}
/**
* @notice calculate debt factoring in decay
* @dev accounts for debt decay since last deposit
* @param _id ID of market
* @return current debt for market in FLOOR decimals
*/
function currentDebt(uint256 _id) public view override returns (uint256) {
return markets[_id].totalDebt - debtDecay(_id);
}
/**
* @notice amount of debt to decay from total debt for market ID
* @param _id ID of market
* @return amount of debt to decay
*/
function debtDecay(uint256 _id) public view override returns (uint64) {
Metadata memory meta = metadata[_id];
uint256 secondsSince = block.timestamp - meta.lastDecay;
return uint64(markets[_id].totalDebt * secondsSince / meta.length);
}
/**
* @notice up to date control variable
* @dev accounts for control variable adjustment
* @param _id ID of market
* @return control variable for market in FLOOR decimals
*/
function currentControlVariable(uint256 _id) public view returns (uint256) {
(uint64 decay,,) = _controlDecay(_id);
return terms[_id].controlVariable - decay;
}
/**
* @notice is a given market accepting deposits
* @param _id ID of market
*/
function isLive(uint256 _id) public view override returns (bool) {
return (markets[_id].capacity != 0 && terms[_id].conclusion > block.timestamp);
}
/**
* @notice returns an array of all active market IDs
*/
function liveMarkets() external view override returns (uint256[] memory) {
uint256 num;
for (uint256 i = 0; i < markets.length; i++) {
if (isLive(i)) num++;
}
uint256[] memory ids = new uint256[](num);
uint256 nonce;
for (uint256 i = 0; i < markets.length; i++) {
if (isLive(i)) {
ids[nonce] = i;
nonce++;
}
}
return ids;
}
/**
* @notice returns an array of all active market IDs for a given quote token
* @param _token quote token to check for
*/
function liveMarketsFor(address _token) external view override returns (uint256[] memory) {
uint256[] memory mkts = marketsForQuote[_token];
uint256 num;
for (uint256 i = 0; i < mkts.length; i++) {
if (isLive(mkts[i])) num++;
}
uint256[] memory ids = new uint256[](num);
uint256 nonce;
for (uint256 i = 0; i < mkts.length; i++) {
if (isLive(mkts[i])) {
ids[nonce] = mkts[i];
nonce++;
}
}
return ids;
}
/* ======== INTERNAL VIEW ======== */
/**
* @notice calculate current market price of quote token in base token
* @dev see marketPrice() for explanation of price computation
* @dev uses info from storage because data has been updated before call (vs marketPrice())
* @param _id market ID
* @return price for market in FLOOR decimals
*/
function _marketPrice(uint256 _id) internal view returns (uint256) {
return
terms[_id].controlVariable
* _debtRatio(_id)
/ (10 ** metadata[_id].quoteDecimals);
}
/**
* @notice calculate debt factoring in decay
* @dev uses info from storage because data has been updated before call (vs debtRatio())
* @param _id market ID
* @return current debt for market in quote decimals
*/
function _debtRatio(uint256 _id) internal view returns (uint256) {
return
markets[_id].totalDebt
* (10 ** metadata[_id].quoteDecimals)
/ treasury.baseSupply();
}
/**
* @notice amount to decay control variable by
* @param _id ID of market
* @return decay_ change in control variable
* @return secondsSince_ seconds since last change in control variable
* @return active_ whether or not change remains active
*/
function _controlDecay(uint256 _id) internal view returns (uint64 decay_, uint48 secondsSince_, bool active_) {
Adjustment memory info = adjustments[_id];
if (!info.active) return (0, 0, false);
secondsSince_ = uint48(block.timestamp) - info.lastAdjustment;
active_ = secondsSince_ < info.timeToAdjusted;
decay_ = active_
? info.change * secondsSince_ / info.timeToAdjusted
: info.change;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.10;
import "../types/FrontEndRewarder.sol";
import "../interfaces/IgFLOOR.sol";
import "../interfaces/IStaking.sol";
import "../interfaces/ITreasury.sol";
import "../interfaces/INoteKeeper.sol";
abstract contract NoteKeeper is INoteKeeper, FrontEndRewarder {
event CreateNote(address user, uint48 bondId, uint256 index, uint256 payout, uint48 expiry);
event PushNote(address oldUser, address newUser, uint256 oldIndex, uint256 newIndex);
event RedeemNote(address user, uint256[] indexes);
mapping(address => Note[]) public notes; // user deposit data
mapping(address => mapping(uint256 => address)) private noteTransfers; // change note ownership
IgFLOOR internal immutable gFLOOR;
IStaking internal immutable staking;
ITreasury internal treasury;
constructor (
IFloorAuthority _authority,
IERC20 _floor,
IgFLOOR _gfloor,
IStaking _staking,
ITreasury _treasury
) FrontEndRewarder(_authority, _floor) {
gFLOOR = _gfloor;
staking = _staking;
treasury = _treasury;
}
// if treasury address changes on authority, update it
function updateTreasury() external {
require(
msg.sender == authority.governor() ||
msg.sender == authority.guardian() ||
msg.sender == authority.policy(),
"Only authorized"
);
treasury = ITreasury(authority.vault());
}
/* ========== ADD ========== */
/**
* @notice adds a new Note for a user, stores the front end & DAO rewards, and mints & stakes payout & rewards
* @param _user the user that owns the Note
* @param _payout the amount of FLOOR due to the user
* @param _expiry the timestamp when the Note is redeemable
* @param _marketID the ID of the market deposited into
* @return index_ the index of the Note in the user's array
*/
function addNote(
address _user,
uint256 _payout,
uint48 _expiry,
uint48 _marketID,
address _referral
) internal returns (uint256 index_) {
// the index of the note is the next in the user's array
index_ = notes[_user].length;
// the new note is pushed to the user's array
notes[_user].push(
Note({
payout: gFLOOR.balanceTo(_payout),
created: uint48(block.timestamp),
matured: _expiry,
redeemed: 0,
marketID: _marketID
})
);
emit CreateNote(_user, _marketID, index_, gFLOOR.balanceTo(_payout), _expiry);
// front end operators can earn rewards by referring users
uint256 rewards = _giveRewards(_payout, _referral);
// mint and stake payout
treasury.mint(address(this), _payout + rewards);
// note that only the payout gets staked (front end rewards are in FLOOR)
staking.stake(address(this), _payout, false, true);
}
/* ========== REDEEM ========== */
/**
* @notice redeem notes for user
* @param _user the user to redeem for
* @param _indexes the note indexes to redeem
* @param _sendgFLOOR send payout as gFLOOR or sFLOOR
* @return payout_ sum of payout sent, in gFLOOR
*/
function redeem(address _user, uint256[] memory _indexes, bool _sendgFLOOR) external override returns (uint256 payout_) {
uint48 time = uint48(block.timestamp);
for (uint256 i = 0; i < _indexes.length; i++) {
(uint256 pay, bool matured) = pendingFor(_user, _indexes[i]);
require(matured, "Depository: note not matured");
if (matured) {
notes[_user][_indexes[i]].redeemed = time; // mark as redeemed
payout_ += pay;
}
}
if (_sendgFLOOR) {
gFLOOR.transfer(_user, payout_); // send payout as gFLOOR
} else {
staking.unwrap(_user, payout_); // unwrap and send payout as sFLOOR
}
emit RedeemNote(_user, _indexes);
}
/* ========== TRANSFER ========== */
/**
* @notice approve an address to transfer a note
* @param _to address to approve note transfer for
* @param _index index of note to approve transfer for
*/
function pushNote(address _to, uint256 _index) external override {
require(notes[msg.sender][_index].created != 0, "Depository: note not found");
noteTransfers[msg.sender][_index] = _to;
}
/**
* @notice transfer a note that has been approved by an address
* @param _from the address that approved the note transfer
* @param _index the index of the note to transfer (in the sender's array)
*/
function pullNote(address _from, uint256 _index) external override returns (uint256 newIndex_) {
require(noteTransfers[_from][_index] == msg.sender, "Depository: transfer not found");
require(notes[_from][_index].redeemed == 0, "Depository: note redeemed");
newIndex_ = notes[msg.sender].length;
notes[msg.sender].push(notes[_from][_index]);
delete notes[_from][_index];
emit PushNote(_from, msg.sender, _index, newIndex_);
}
/* ========== VIEW ========== */
// Note info
/**
* @notice all pending notes for user
* @param _user the user to query notes for
* @return the pending notes for the user
*/
function indexesFor(address _user) public view override returns (uint256[] memory) {
Note[] memory info = notes[_user];
uint256 length;
for (uint256 i = 0; i < info.length; i++) {
if (info[i].redeemed == 0 && info[i].payout != 0) length++;
}
uint256[] memory indexes = new uint256[](length);
uint256 position;
for (uint256 i = 0; i < info.length; i++) {
if (info[i].redeemed == 0 && info[i].payout != 0) {
indexes[position] = i;
position++;
}
}
return indexes;
}
/**
* @notice calculate amount available for claim for a single note
* @param _user the user that the note belongs to
* @param _index the index of the note in the user's array
* @return payout_ the payout due, in gFLOOR
* @return matured_ if the payout can be redeemed
*/
function pendingFor(address _user, uint256 _index) public view override returns (uint256 payout_, bool matured_) {
Note memory note = notes[_user][_index];
payout_ = note.payout;
matured_ = note.redeemed == 0 && note.matured <= block.timestamp && note.payout != 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.5;
import {IERC20} from "../interfaces/IERC20.sol";
/// @notice Safe IERC20 and ETH transfer library that safely handles missing return values.
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol)
/// Taken from Solmate
library SafeERC20 {
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED");
}
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.transfer.selector, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED");
}
function safeApprove(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.approve.selector, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED");
}
function safeTransferETH(address to, uint256 amount) internal {
(bool success, ) = to.call{value: amount}(new bytes(0));
require(success, "ETH_TRANSFER_FAILED");
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.7.5;
import "./IERC20.sol";
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
import "./IERC20.sol";
interface IBondDepository {
// Info about each type of market
struct Market {
uint256 capacity; // capacity remaining
IERC20 quoteToken; // token to accept as payment
bool capacityInQuote; // capacity limit is in payment token (true) or in FLOOR (false, default)
uint64 totalDebt; // total debt from market
uint64 maxPayout; // max tokens in/out (determined by capacityInQuote false/true, respectively)
uint64 sold; // base tokens out
uint256 purchased; // quote tokens in
}
// Info for creating new markets
struct Terms {
bool fixedTerm; // fixed term or fixed expiration
uint64 controlVariable; // scaling variable for price
uint48 vesting; // length of time from deposit to maturity if fixed-term
uint48 conclusion; // timestamp when market no longer offered (doubles as time when market matures if fixed-expiry)
uint64 maxDebt; // 9 decimal debt maximum in FLOOR
}
// Additional info about market.
struct Metadata {
uint48 lastTune; // last timestamp when control variable was tuned
uint48 lastDecay; // last timestamp when market was created and debt was decayed
uint48 length; // time from creation to conclusion. used as speed to decay debt.
uint48 depositInterval; // target frequency of deposits
uint48 tuneInterval; // frequency of tuning
uint8 quoteDecimals; // decimals of quote token
}
// Control variable adjustment data
struct Adjustment {
uint64 change;
uint48 lastAdjustment;
uint48 timeToAdjusted;
bool active;
}
/**
* @notice deposit market
* @param _bid uint256
* @param _amount uint256
* @param _maxPrice uint256
* @param _user address
* @param _referral address
* @return payout_ uint256
* @return expiry_ uint256
* @return index_ uint256
*/
function deposit(
uint256 _bid,
uint256 _amount,
uint256 _maxPrice,
address _user,
address _referral
) external returns (
uint256 payout_,
uint256 expiry_,
uint256 index_
);
function create (
IERC20 _quoteToken, // token used to deposit
uint256[3] memory _market, // [capacity, initial price]
bool[2] memory _booleans, // [capacity in quote, fixed term]
uint256[2] memory _terms, // [vesting, conclusion]
uint32[2] memory _intervals // [deposit interval, tune interval]
) external returns (uint256 id_);
function close(uint256 _id) external;
function isLive(uint256 _bid) external view returns (bool);
function liveMarkets() external view returns (uint256[] memory);
function liveMarketsFor(address _quoteToken) external view returns (uint256[] memory);
function payoutFor(uint256 _amount, uint256 _bid) external view returns (uint256);
function marketPrice(uint256 _bid) external view returns (uint256);
function currentDebt(uint256 _bid) external view returns (uint256);
function debtRatio(uint256 _bid) external view returns (uint256);
function debtDecay(uint256 _bid) external view returns (uint64);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.10;
import "../types/FloorAccessControlled.sol";
import "../interfaces/IERC20.sol";
abstract contract FrontEndRewarder is FloorAccessControlled {
/* ========= STATE VARIABLES ========== */
uint256 public daoReward; // % reward for dao (3 decimals: 100 = 1%)
uint256 public refReward; // % reward for referrer (3 decimals: 100 = 1%)
mapping(address => uint256) public rewards; // front end operator rewards
mapping(address => bool) public whitelisted; // whitelisted status for operators
IERC20 internal immutable floor; // reward token
constructor(
IFloorAuthority _authority,
IERC20 _floor
) FloorAccessControlled(_authority) {
floor = _floor;
}
/* ========= EXTERNAL FUNCTIONS ========== */
// pay reward to front end operator
function getReward() external {
uint256 reward = rewards[msg.sender];
rewards[msg.sender] = 0;
floor.transfer(msg.sender, reward);
}
/* ========= INTERNAL ========== */
/**
* @notice add new market payout to user data
*/
function _giveRewards(
uint256 _payout,
address _referral
) internal returns (uint256) {
// first we calculate rewards paid to the DAO and to the front end operator (referrer)
uint256 toDAO = _payout * daoReward / 1e4;
uint256 toRef = _payout * refReward / 1e4;
// and store them in our rewards mapping
if (whitelisted[_referral]) {
rewards[_referral] += toRef;
rewards[authority.guardian()] += toDAO;
} else { // the DAO receives both rewards if referrer is not whitelisted
rewards[authority.guardian()] += toDAO + toRef;
}
return toDAO + toRef;
}
/**
* @notice set rewards for front end operators and DAO
*/
function setRewards(uint256 _toFrontEnd, uint256 _toDAO) external onlyGovernor {
refReward = _toFrontEnd;
daoReward = _toDAO;
}
/**
* @notice add or remove addresses from the reward whitelist
*/
function whitelist(address _operator) external onlyPolicy {
whitelisted[_operator] = !whitelisted[_operator];
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.7.5;
import "./IERC20.sol";
interface IgFLOOR is IERC20 {
function mint(address _to, uint256 _amount) external;
function burn(address _from, uint256 _amount) external;
function index() external view returns (uint256);
function balanceFrom(uint256 _amount) external view returns (uint256);
function balanceTo(uint256 _amount) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.7.5;
interface IStaking {
function stake(
address _to,
uint256 _amount,
bool _rebasing,
bool _claim
) external returns (uint256);
function claim(address _recipient, bool _rebasing) external returns (uint256);
function forfeit() external returns (uint256);
function toggleLock() external;
function unstake(
address _to,
uint256 _amount,
bool _trigger,
bool _rebasing
) external returns (uint256);
function wrap(address _to, uint256 _amount) external returns (uint256 gBalance_);
function unwrap(address _to, uint256 _amount) external returns (uint256 sBalance_);
function rebase() external;
function index() external view returns (uint256);
function contractBalance() external view returns (uint256);
function totalStaked() external view returns (uint256);
function supplyInWarmup() external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.7.5;
interface ITreasury {
function bondCalculator(address _address) external view returns (address);
function deposit(uint256 _amount, address _token, uint256 _profit) external returns (uint256);
function withdraw(uint256 _amount, address _token) external;
function depositERC721(address _token, uint256 _tokenId) external;
function withdrawERC721(address _token, uint256 _tokenId) external;
function tokenValue(address _token, uint256 _amount) external view returns (uint256 value_);
function mint(address _recipient, uint256 _amount) external;
function manage(address _token, uint256 _amount) external;
function allocatorManage(address _token, uint256 _amount) external;
function claimNFTXRewards(address _liquidityStaking, uint256 _vaultId, address _rewardToken) external;
function incurDebt(uint256 amount_, address token_) external;
function repayDebtWithReserve(uint256 amount_, address token_) external;
function excessReserves() external view returns (uint256);
function riskOffValuation(address _token) external view returns (uint256);
function baseSupply() external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.5;
interface INoteKeeper {
// Info for market note
struct Note {
uint256 payout; // gFLOOR remaining to be paid
uint48 created; // time market was created
uint48 matured; // timestamp when market is matured
uint48 redeemed; // time market was redeemed
uint48 marketID; // market ID of deposit. uint48 to avoid adding a slot.
}
function redeem(address _user, uint256[] memory _indexes, bool _sendgFLOOR) external returns (uint256);
function pushNote(address to, uint256 index) external;
function pullNote(address from, uint256 index) external returns (uint256 newIndex_);
function indexesFor(address _user) external view returns (uint256[] memory);
function pendingFor(address _user, uint256 _index) external view returns (uint256 payout_, bool matured_);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.5;
import "../interfaces/IFloorAuthority.sol";
abstract contract FloorAccessControlled {
/* ========== EVENTS ========== */
event AuthorityUpdated(IFloorAuthority indexed authority);
string UNAUTHORIZED = "UNAUTHORIZED"; // save gas
/* ========== STATE VARIABLES ========== */
IFloorAuthority public authority;
/* ========== Constructor ========== */
constructor(IFloorAuthority _authority) {
authority = _authority;
emit AuthorityUpdated(_authority);
}
/* ========== MODIFIERS ========== */
modifier onlyGovernor() {
require(msg.sender == authority.governor(), UNAUTHORIZED);
_;
}
modifier onlyGuardian() {
require(msg.sender == authority.guardian(), UNAUTHORIZED);
_;
}
modifier onlyPolicy() {
require(msg.sender == authority.policy(), UNAUTHORIZED);
_;
}
modifier onlyVault() {
require(msg.sender == authority.vault(), UNAUTHORIZED);
_;
}
/* ========== GOV ONLY ========== */
function setAuthority(IFloorAuthority _newAuthority) external onlyGovernor {
authority = _newAuthority;
emit AuthorityUpdated(_newAuthority);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.7.5;
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: AGPL-3.0-or-later
pragma solidity >=0.7.5;
interface IFloorAuthority {
/* ========== EVENTS ========== */
event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event GovernorPulled(address indexed from, address indexed to);
event GuardianPulled(address indexed from, address indexed to);
event PolicyPulled(address indexed from, address indexed to);
event VaultPulled(address indexed from, address indexed to);
/* ========== VIEW ========== */
function governor() external view returns (address);
function guardian() external view returns (address);
function policy() external view returns (address);
function vault() external view returns (address);
} | calculate debt factoring in decay uses info from storage because data has been updated before call (vs debtRatio()) _id market ID return current debt for market in quote decimals/ | function _debtRatio(uint256 _id) internal view returns (uint256) {
return
markets[_id].totalDebt
* (10 ** metadata[_id].quoteDecimals)
/ treasury.baseSupply();
}
| 10,010,492 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract PKI {
modifier onlyTrustedCA{
require(checkIfTrustedCA(msg.sender), "Only Trusted CAs are allowed");
_;
}
struct domain_data{
string domainName;
string organization;
string country;
string state;
string emailAddr;
string publicKey;
uint daysValid;
uint256 dateCreated;
uint revokedByCount;
bool valid;
address paymentAddr;
bool[] isRevokedBy;
}
struct petition{ //those who want to become a CA
address petitioner;
uint8 timeLapsed;
uint8 votesReceived;
address[] voters;
bool added;
}
address [] public owners;
petition [] public petitions;
mapping(string => domain_data) public domain_name_map; //details of a single domain
string [] public domainArray; //all domain names
//change the below addresses to the ones in your own ganache workspace
constructor(){
owners.push(0x5Dd5d1def7f67E5f0B977dB341d7774F2ccC89b5);
owners.push(0x2621922fFB7BF8b052aDa0cDBB0E2Bb15E6692dD);
owners.push(0x8FB7452f0A4CddC463b3241A47Eb0Db5feeE01A3);
owners.push(0x16dF74a6DbE94aa3FC3834e5A6589ec473e34f14);
owners.push(0x263202fC6a8E70F58079859349F34dC1f82184F1);
owners.push(0x4A896995f0C53a52D58381c22D137C25a7879AA8);
owners.push(0x251018F4C3dcf280205D5D24770806ef14a90B42);
owners.push(0x24524E2Fb653E06E001A9498c1c0B616e4d12F21);
//owners.push(0x5C626149C2b5d1f199292a4C446D9f667758DfdA);
//owners.push(0x5eF34402dD52aC15A6dE46490Eda54005EE4038f);
}
function vote(address _petitioner) public onlyTrustedCA{
for (uint i=0; i<petitions.length;i++){
//first increment time lapsed for all petitions
petitions[i].timeLapsed+=1;
}
for (uint i=0; i<petitions.length; i++){
//add vote of the person being voted for
if (petitions[i].petitioner==_petitioner){
require(checkIfVoted(msg.sender, petitions[i].voters)==false, "You've already voted for them");
require(petitions[i].added==false, "They're already added to authorities");
petitions[i].votesReceived+=1;
petitions[i].voters.push(msg.sender);
}
//next check if any votes for any petitions have reached the threshold, if so they should be added to trusted CAs list
//and their revoke status for all domains set to false
if (petitions[i].votesReceived>=3 && petitions[i].added==false){
owners.push(petitions[i].petitioner); //add to trusted
for (uint j=0; j<domainArray.length; j++){
domain_name_map[domainArray[j]].isRevokedBy.push(false); //set domain's revoke to false
}
petitions[i].added=true;
}
//check if any that have not receieved needed votes have been in the petitioner array for more than 10 votes, if so, remove them
if (petitions[i].timeLapsed>=4 && petitions[i].added==false){ //actually 10
removePetition(petitions[i].petitioner);
}
}
}
//call this function in order to submit a petition if you want to become a Trusted CA
function submitCAPetition() public{
for(uint i=0; i<petitions.length; i++){
if (petitions[i].petitioner==msg.sender){
revert("You already have a pending a petition");
}
}
require(checkIfTrustedCA(msg.sender)==false, "You are already a CA!");
petition memory temp;
temp.petitioner=msg.sender;
temp.timeLapsed=0;
temp.votesReceived=0;
temp.added=false;
petitions.push(temp);
}
function viewPetitions() view public returns(petition[] memory){
return petitions;
}
//call this function to remove a petition from petitioner array
function removePetition(address petitioner) public {
for (uint i = 0;i<petitions.length; i++){
if (petitions[i].petitioner==petitioner){
petitions[i] = petitions[petitions.length-1];
delete petitions[petitions.length-1];
petitions.pop();
break;
}
}
}
//call this function to check if a voter has already voted for this petitioner
function checkIfVoted(address _voter, address[] memory _voters) public view returns(bool){
bool voted=false;
for (uint i=0; i<_voters.length; i++){
if (_voters[i]==_voter){
voted=true;
}
}
return voted;
}
function checkIfTrustedCA(address trustedca) public view returns(bool trust){
bool canWeTrust = false;
for(uint i=0;i<owners.length;i++){
if(trustedca==owners[i]){
canWeTrust = true;
}
}
return canWeTrust;
}
function checkIfDomainUsed(string memory domain) public view returns(bool isUsed){
bool isUsed=false;
for (uint i=0; i<domainArray.length; i++){
if (keccak256(bytes(domainArray[i]))==keccak256(bytes(domain))){
isUsed=true;
}
}
return isUsed;
}
function getDomains() view public returns(string[] memory){
return domainArray;
}
function registerDomain(string memory domainName, string memory organization,
string memory country, string memory state, string memory emailAddr,
string memory publicKey, uint daysValid) public onlyTrustedCA {
// domain - the one being registered
// Every address has one or many domains registered to it
// Add all the values associated with the domain
require(checkIfDomainUsed(domainName)==false, "Domain already exists"); // Domain should not exist before
domainArray.push(domainName);
//domainExists[domainName] = true;
// mapping to domain name
domain_name_map[domainName].domainName=domainName;
domain_name_map[domainName].organization=organization;
domain_name_map[domainName].country=country;
domain_name_map[domainName].state=state;
domain_name_map[domainName].emailAddr=emailAddr;
domain_name_map[domainName].publicKey=publicKey;
domain_name_map[domainName].daysValid = daysValid;
domain_name_map[domainName].dateCreated = block.timestamp;
domain_name_map[domainName].revokedByCount = 0;
domain_name_map[domainName].paymentAddr = msg.sender;
domain_name_map[domainName].valid = true;
for(uint i=0; i<owners.length;i++){
domain_name_map[domainName].isRevokedBy.push(false);
}
}
/*
function getDomainData(string memory domainName) view public returns (string[] memory,
string[] memory, string[] memory,string[] memory,string[] memory,uint,uint256,bool ){
return(domain_name_map[domainName].organization, domain_name_map[domainName].country,
domain_name_map[domainName].state, domain_name_map[domainName].emailAddr,
domain_name_map[domainName].publicKey, domain_name_map[domainName].daysValid,
domain_name_map[domainName].dateCreated,domain_name_map[domainName].isCertified);
}
*/
// return all values corresponding to a domain name as one string
function getDomainData(string memory domainName) view public returns (domain_data memory){
//return ("Domain Name: "+domain_name_map[domainName].domainName+"\"+"Organization: "+domain_name_map[domain_name_map].organization);
return (domain_name_map[domainName]);
}
//return organization of domain
function getOrganization(string memory domainName) view public returns (string memory org){
return (domain_name_map[domainName].organization);
}
//return country of domain
function getCountry(string memory domainName) view public returns (string memory con){
return (domain_name_map[domainName].country);
}
//return registered email of domain
function getEmail(string memory domainName) view public returns (string memory email){
return (domain_name_map[domainName].emailAddr);
}
//return public key of domain
function getKey(string memory domainName) view public returns (string memory key){
return (domain_name_map[domainName].publicKey);
}
//return address of domain holder
function getAddress(string memory domainName) view public returns (address){
return (domain_name_map[domainName].paymentAddr);
}
//return creation date of domain
function getCreationDate(string memory domainName) view public returns (uint256){
return (domain_name_map[domainName].dateCreated);
}
//return which CA have and havent revoked domain
function getCARevokeStatus(string memory domainName) view public returns (address[] memory, bool[] memory){
return (owners, domain_name_map[domainName].isRevokedBy);
}
function updatePublicKey(string memory domainName, string memory publicKeyNew) public onlyTrustedCA{
domain_name_map[domainName].publicKey=publicKeyNew;
}
function updateDaysOfContract(string memory domainName, uint newDay) public onlyTrustedCA{
domain_name_map[domainName].daysValid=newDay;
}
function getOwnerIndex(address ad) private returns(uint){
for(uint i=0;i<owners.length;i++){
if(ad == owners[i]){
return i;
}
}
return 1000;
}
function removeDomain(string memory domainName) public onlyTrustedCA {
for (uint i = 0; i<domainArray.length; i++){
if (keccak256(abi.encodePacked(domainArray[i]))==keccak256(abi.encodePacked(domainName))){
domainArray[i] = domainArray[domainArray.length-1];
delete domainArray[domainArray.length-1];
domainArray.pop();
break;
}
}
}
// or should every domain be valid at the time of registration
function revokeDomain(string memory domainName) public onlyTrustedCA{
// Only the CA can revoke a domain
// maintain count how many CAs revoked a domain
// every domain has a mapping of CA and mapping true or false.
require(verifyDomain(domainName), "Verify Domain name valid");
require(domain_name_map[domainName].isRevokedBy[getOwnerIndex(msg.sender)]==false, "Verify if the domain has not been previously revoked");
domain_name_map[domainName].isRevokedBy[getOwnerIndex(msg.sender)]=true;
domain_name_map[domainName].revokedByCount +=1;
// If 3 CAs reovke a contract only then set valid to false
if (domain_name_map[domainName].revokedByCount >=3){
domain_name_map[domainName].valid = false;
removeDomain(domainName);
}
}
function verifyDomain(string memory domainName) view public returns(bool){
return domain_name_map[domainName].valid;
// Also verify from the timestamp - is the certificate valid anymore?
}
function getCAs() view public returns (address[] memory){
return owners;
}
}
// myins.registerDomain("www.a.com","f","p","d","d","s",23, {from: '0x9351eb4413BF082Ab6Adc1236cE7b3b791D89457'})
/*
****************checking voting***********
x.submitCAPetition({from:"0x5eF34402dD52aC15A6dE46490Eda54005EE4038f"})
x.submitCAPetition({from:"0x5C626149C2b5d1f199292a4C446D9f667758DfdA"})
x.viewPetitions()
x.vote("0x5eF34402dD52aC15A6dE46490Eda54005EE4038f")
x.vote("0x5eF34402dD52aC15A6dE46490Eda54005EE4038f", {from:"0x9129122c55b1055Bad9d9B56D50A19968a9db944"})
x.viewPetitions()
x.vote("0x5eF34402dD52aC15A6dE46490Eda54005EE4038f", {from:"0x54A49513BFdFdfdfe1D2d86709e2E8bFAF68081c"})
x.vote("0x5C626149C2b5d1f199292a4C446D9f667758DfdA", {from:"0x54A49513BFdFdfdfe1D2d86709e2E8bFAF68081c"})
x.viewPetitions()
x.getCAs()
*/ | / return all values corresponding to a domain name as one stringreturn ("Domain Name: "+domain_name_map[domainName].domainName+"\"+"Organization: "+domain_name_map[domain_name_map].organization); | function getDomainData(string memory domainName) view public returns (domain_data memory){
return (domain_name_map[domainName]);
}
| 7,298,851 |
// SPDX-License-Identifier: GPL-2.0
pragma solidity 0.8.8;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
interface IUniswapV2Pair {
function token0() external pure returns (address);
function token1() external pure returns (address);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
abstract contract Zap {
using SafeERC20 for IERC20;
using SafeMath for uint256;
IERC20 public immutable koromaru; // Koromaru token
IERC20 public immutable koromaruUniV2; // Uniswap V2 LP token for Koromaru
IUniswapV2Factory public immutable UniSwapV2FactoryAddress;
IUniswapV2Router02 public uniswapRouter;
address public immutable WETHAddress;
uint256 private constant swapDeadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
struct ZapVariables {
uint256 LP;
uint256 koroAmount;
uint256 wethAmount;
address tokenToZap;
uint256 amountToZap;
}
event ZappedIn(address indexed account, uint256 amount);
event ZappedOut(
address indexed account,
uint256 amount,
uint256 koroAmount,
uint256 Eth
);
constructor(
address _koromaru,
address _koromaruUniV2,
address _UniSwapV2FactoryAddress,
address _uniswapRouter
) {
koromaru = IERC20(_koromaru);
koromaruUniV2 = IERC20(_koromaruUniV2);
UniSwapV2FactoryAddress = IUniswapV2Factory(_UniSwapV2FactoryAddress);
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
WETHAddress = uniswapRouter.WETH();
}
function ZapIn(uint256 _amount, bool _multi)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
(uint256 _koroAmount, uint256 _ethAmount) = _moveTokensToContract(
_amount
);
_approveRouterIfNotApproved();
(_LP, _WETHBalance, _KoromaruBalance) = !_multi
? _zapIn(_koroAmount, _ethAmount)
: _zapInMulti(_koroAmount, _ethAmount);
require(_LP > 0, "ZapIn: Invalid LP amount");
emit ZappedIn(msg.sender, _LP);
}
function zapOut(uint256 _koroLPAmount)
internal
returns (uint256 _koroTokens, uint256 _ether)
{
_approveRouterIfNotApproved();
uint256 balanceBefore = koromaru.balanceOf(address(this));
_ether = uniswapRouter.removeLiquidityETHSupportingFeeOnTransferTokens(
address(koromaru),
_koroLPAmount,
1,
1,
address(this),
swapDeadline
);
require(_ether > 0, "ZapOut: Eth Output Low");
uint256 balanceAfter = koromaru.balanceOf(address(this));
require(balanceAfter > balanceBefore, "ZapOut: Nothing to ZapOut");
_koroTokens = balanceAfter.sub(balanceBefore);
emit ZappedOut(msg.sender, _koroLPAmount, _koroTokens, _ether);
}
//-------------------- Zap Utils -------------------------
function _zapIn(uint256 _koroAmount, uint256 _wethAmount)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
ZapVariables memory zapVars;
zapVars.tokenToZap; // koro or eth
zapVars.amountToZap; // koro or weth
(address _Token0, address _Token1) = _getKoroLPPairs(
address(koromaruUniV2)
);
if (_koroAmount > 0 && _wethAmount < 1) {
// if only koro
zapVars.amountToZap = _koroAmount;
zapVars.tokenToZap = address(koromaru);
} else if (_wethAmount > 0 && _koroAmount < 1) {
// if only weth
zapVars.amountToZap = _wethAmount;
zapVars.tokenToZap = WETHAddress;
}
(uint256 token0Out, uint256 token1Out) = _executeSwapForPairs(
zapVars.tokenToZap,
_Token0,
_Token1,
zapVars.amountToZap
);
(_LP, _WETHBalance, _KoromaruBalance) = _toLiquidity(
_Token0,
_Token1,
token0Out,
token1Out
);
}
function _zapInMulti(uint256 _koroAmount, uint256 _wethAmount)
internal
returns (
uint256 _LPToken,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
ZapVariables memory zapVars;
zapVars.koroAmount = _koroAmount;
zapVars.wethAmount = _wethAmount;
zapVars.tokenToZap; // koro or eth
zapVars.amountToZap; // koro or weth
{
(
uint256 _kLP,
uint256 _kWETHBalance,
uint256 _kKoromaruBalance
) = _zapIn(zapVars.koroAmount, 0);
_LPToken += _kLP;
_WETHBalance += _kWETHBalance;
_KoromaruBalance += _kKoromaruBalance;
}
{
(
uint256 _kLP,
uint256 _kWETHBalance,
uint256 _kKoromaruBalance
) = _zapIn(0, zapVars.wethAmount);
_LPToken += _kLP;
_WETHBalance += _kWETHBalance;
_KoromaruBalance += _kKoromaruBalance;
}
}
function _toLiquidity(
address _Token0,
address _Token1,
uint256 token0Out,
uint256 token1Out
)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
_approveToken(_Token0, address(uniswapRouter), token0Out);
_approveToken(_Token1, address(uniswapRouter), token1Out);
(uint256 amountA, uint256 amountB, uint256 LP) = uniswapRouter
.addLiquidity(
_Token0,
_Token1,
token0Out,
token1Out,
1,
1,
address(this),
swapDeadline
);
_LP = LP;
_WETHBalance = token0Out.sub(amountA);
_KoromaruBalance = token1Out.sub(amountB);
}
function _approveRouterIfNotApproved() private {
if (koromaru.allowance(address(this), address(uniswapRouter)) == 0) {
koromaru.approve(address(uniswapRouter), type(uint256).max);
}
if (
koromaruUniV2.allowance(address(this), address(uniswapRouter)) == 0
) {
koromaruUniV2.approve(address(uniswapRouter), type(uint256).max);
}
}
function _moveTokensToContract(uint256 _amount)
internal
returns (uint256 _koroAmount, uint256 _ethAmount)
{
_ethAmount = msg.value;
if (msg.value > 0) IWETH(WETHAddress).deposit{value: _ethAmount}();
if (msg.value < 1) {
// ZapIn must have either both Koro and Eth, just Eth or just Koro
require(_amount > 0, "KOROFARM: Invalid ZapIn Call");
}
if (_amount > 0) {
koromaru.safeTransferFrom(msg.sender, address(this), _amount);
}
_koroAmount = _amount;
}
function _getKoroLPPairs(address _pairAddress)
internal
pure
returns (address token0, address token1)
{
IUniswapV2Pair uniPair = IUniswapV2Pair(_pairAddress);
token0 = uniPair.token0();
token1 = uniPair.token1();
}
function _executeSwapForPairs(
address _inToken,
address _token0,
address _token1,
uint256 _amount
) internal returns (uint256 _token0Out, uint256 _token1Out) {
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
if (_inToken == _token0) {
uint256 swapAmount = determineSwapInAmount(resv0, _amount);
if (swapAmount < 1) swapAmount = _amount.div(2);
// swap Weth tokens to koro
_token1Out = _swapTokenForToken(_inToken, _token1, swapAmount);
_token0Out = _amount.sub(swapAmount);
} else {
uint256 swapAmount = determineSwapInAmount(resv1, _amount);
if (swapAmount < 1) swapAmount = _amount.div(2);
_token0Out = _swapTokenForToken(_inToken, _token0, swapAmount);
_token1Out = _amount.sub(swapAmount);
}
}
function _swapTokenForToken(
address _swapFrom,
address _swapTo,
uint256 _tokensToSwap
) internal returns (uint256 tokenBought) {
if (_swapFrom == _swapTo) {
return _tokensToSwap;
}
_approveToken(
_swapFrom,
address(uniswapRouter),
_tokensToSwap.mul(1e12)
);
address pair = UniSwapV2FactoryAddress.getPair(_swapFrom, _swapTo);
require(pair != address(0), "SwapTokenForToken: Swap path error");
address[] memory path = new address[](2);
path[0] = _swapFrom;
path[1] = _swapTo;
uint256 balanceBefore = IERC20(_swapTo).balanceOf(address(this));
uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
_tokensToSwap,
0,
path,
address(this),
swapDeadline
);
uint256 balanceAfter = IERC20(_swapTo).balanceOf(address(this));
tokenBought = balanceAfter.sub(balanceBefore);
// Ideal, but fails to work with Koromary due to fees
// tokenBought = uniswapRouter.swapExactTokensForTokens(
// _tokensToSwap,
// 1,
// path,
// address(this),
// swapDeadline
// )[path.length - 1];
// }
require(tokenBought > 0, "SwapTokenForToken: Error Swapping Tokens 2");
}
function determineSwapInAmount(uint256 _pairResIn, uint256 _userAmountIn)
internal
pure
returns (uint256)
{
return
(_sqrt(
_pairResIn *
((_userAmountIn * 3988000) + (_pairResIn * 3988009))
) - (_pairResIn * 1997)) / 1994;
}
function _sqrt(uint256 _val) internal pure returns (uint256 z) {
if (_val > 3) {
z = _val;
uint256 x = _val / 2 + 1;
while (x < z) {
z = x;
x = (_val / x + x) / 2;
}
} else if (_val != 0) {
z = 1;
}
}
function _approveToken(
address token,
address spender,
uint256 amount
) internal {
IERC20 _token = IERC20(token);
_token.safeApprove(spender, 0);
_token.safeApprove(spender, amount);
}
//---------------- End of Zap Utils ----------------------
}
contract KoroFarms is Ownable, Pausable, ReentrancyGuard, Zap {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
struct UserInfo {
uint256 amount;
uint256 koroDebt;
uint256 ethDebt;
uint256 unpaidKoro;
uint256 unpaidEth;
uint256 lastRewardHarvestedTime;
}
struct FarmInfo {
uint256 accKoroRewardsPerShare;
uint256 accEthRewardsPerShare;
uint256 lastRewardTimestamp;
}
AggregatorV3Interface internal priceFeed;
uint256 internal immutable koromaruDecimals;
uint256 internal constant EthPriceFeedDecimal = 1e8;
uint256 internal constant precisionScaleUp = 1e30;
uint256 internal constant secsPerDay = 1 days / 1 seconds;
uint256 private taxRefundPercentage;
uint256 internal constant _1hundred_Percent = 10000;
uint256 public APR; // 100% = 10000, 50% = 5000, 15% = 1500
uint256 rewardHarvestingInterval;
uint256 public koroRewardAllocation;
uint256 public ethRewardAllocation;
uint256 internal maxLPLimit;
uint256 internal zapKoroLimit;
FarmInfo public farmInfo;
mapping(address => UserInfo) public userInfo;
uint256 public totalEthRewarded; // total amount of eth given as rewards
uint256 public totalKoroRewarded; // total amount of Koro given as rewards
//---------------- Contract Events -------------------
event Compound(address indexed account, uint256 koro, uint256 eth);
event Withdraw(address indexed account, uint256 amount);
event Deposit(address indexed account, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event KoroRewardsHarvested(address indexed account, uint256 Kororewards);
event EthRewardsHarvested(address indexed account, uint256 Ethrewards);
event APRUpdated(uint256 OldAPR, uint256 NewAPR);
event Paused();
event Unpaused();
event IncreaseKoroRewardPool(uint256 amount);
event IncreaseEthRewardPool(uint256 amount);
//------------- End of Contract Events ----------------
constructor(
address _koromaru,
address _koromaruUniV2,
address _UniSwapV2FactoryAddress,
address _uniswapRouter,
uint256 _apr,
uint256 _taxToRefund,
uint256 _koromaruTokenDecimals,
uint256 _koroRewardAllocation,
uint256 _rewardHarvestingInterval,
uint256 _zapKoroLimit
) Zap(_koromaru, _koromaruUniV2, _UniSwapV2FactoryAddress, _uniswapRouter) {
require(
_koroRewardAllocation <= 10000,
"setRewardAllocations: Invalid rewards allocation"
);
require(_apr <= 10000, "SetDailyAPR: Invalid APR Value");
approveRouterIfNotApproved();
koromaruDecimals = 10**_koromaruTokenDecimals;
zapKoroLimit = _zapKoroLimit * 10**_koromaruTokenDecimals;
APR = _apr;
koroRewardAllocation = _koroRewardAllocation;
ethRewardAllocation = _1hundred_Percent.sub(_koroRewardAllocation);
taxRefundPercentage = _taxToRefund;
farmInfo = FarmInfo({
lastRewardTimestamp: block.timestamp,
accKoroRewardsPerShare: 0,
accEthRewardsPerShare: 0
});
rewardHarvestingInterval = _rewardHarvestingInterval * 1 seconds;
priceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
}
//---------------- Contract Owner ----------------------
/**
* @notice Update chainLink Eth Price feed
*/
function updatePriceFeed(address _usdt_eth_aggregator) external onlyOwner {
priceFeed = AggregatorV3Interface(_usdt_eth_aggregator);
}
/**
* @notice Set's tax refund percentage for Koromaru
* @dev User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setTaxRefundPercent(uint256 _taxToRefund) external onlyOwner {
taxRefundPercentage = _taxToRefund;
}
/**
* @notice Set's max koromaru per transaction
* @dev Decimals will be added automatically
*/
function setZapLimit(uint256 _limit) external onlyOwner {
zapKoroLimit = _limit * koromaruDecimals;
}
/**
* @notice Set's daily ROI percentage for the farm
* @dev User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setDailyAPR(uint256 _dailyAPR) external onlyOwner {
updateFarm();
require(_dailyAPR <= 10000, "SetDailyAPR: Invalid APR Value");
uint256 oldAPr = APR;
APR = _dailyAPR;
emit APRUpdated(oldAPr, APR);
}
/**
* @notice Set's reward allocation for reward pool
* @dev Set for Koromaru only, eth's allocation will be calcuated. User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setRewardAllocations(uint256 _koroAllocation) external onlyOwner {
// setting 10000 (100%) will set eth rewards to 0.
require(
_koroAllocation <= 10000,
"setRewardAllocations: Invalid rewards allocation"
);
koroRewardAllocation = _koroAllocation;
ethRewardAllocation = _1hundred_Percent.sub(_koroAllocation);
}
/**
* @notice Set's maximum amount of LPs that can be staked in this farm
* @dev When 0, no limit is imposed. When max is reached farmers cannot stake more LPs or compound.
*/
function setMaxLPLimit(uint256 _maxLPLimit) external onlyOwner {
// A new user’s stake cannot cause the amount of LP tokens in the farm to exceed this value
// MaxLP can be set to 0(nomax)
maxLPLimit = _maxLPLimit;
}
/**
* @notice Reset's the chainLink price feed to the default price feed
*/
function resetPriceFeed() external onlyOwner {
priceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
}
/**
* @notice Withdraw foreign tokens sent to this contract
* @dev Can only withdraw none koromaru tokens and KoroV2 tokens
*/
function withdrawForeignToken(address _token)
external
nonReentrant
onlyOwner
{
require(_token != address(0), "KOROFARM: Invalid Token");
require(
_token != address(koromaru),
"KOROFARM: Token cannot be same as koromaru tokens"
);
require(
_token != address(koromaruUniV2),
"KOROFARM: Token cannot be same as farmed tokens"
);
uint256 amount = IERC20(_token).balanceOf(address(this));
if (amount > 0) {
IERC20(_token).safeTransfer(msg.sender, amount);
}
}
/**
* @notice Deposit Koromaru tokens into reward pool
*/
function depositKoroRewards(uint256 _amount)
external
onlyOwner
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid Koro Amount");
koromaru.safeTransferFrom(msg.sender, address(this), _amount);
emit IncreaseKoroRewardPool(_amount);
}
/**
* @notice Deposit Eth tokens into reward pool
*/
function depositEthRewards() external payable onlyOwner nonReentrant {
require(msg.value > 0, "KOROFARM: Invalid Eth Amount");
emit IncreaseEthRewardPool(msg.value);
}
/**
* @notice This function will pause the farm and withdraw all rewards in case of failure or emergency
*/
function pauseAndRemoveRewardPools() external onlyOwner whenNotPaused {
// only to be used by admin in critical situations
uint256 koroBalance = koromaru.balanceOf(address(this));
uint256 ethBalance = payable(address(this)).balance;
if (koroBalance > 0) {
koromaru.safeTransfer(msg.sender, koroBalance);
}
if (ethBalance > 0) {
(bool sent, ) = payable(msg.sender).call{value: ethBalance}("");
require(sent, "Failed to send Ether");
}
}
/**
* @notice Initiate stopped state
* @dev Only possible when contract not paused.
*/
function pause() external onlyOwner whenNotPaused {
_pause();
emit Paused();
}
/**
* @notice Initiate normal state
* @dev Only possible when contract is paused.
*/
function unpause() external onlyOwner whenPaused {
_unpause();
emit Unpaused();
}
//-------------- End Contract Owner --------------------
//---------------- Contract Farmer ----------------------
/**
* @notice Calculates and returns pending rewards for a farmer
*/
function getPendingRewards(address _farmer)
public
view
returns (uint256 pendinKoroTokens, uint256 pendingEthWei)
{
UserInfo storage user = userInfo[_farmer];
uint256 accKoroRewardsPerShare = farmInfo.accKoroRewardsPerShare;
uint256 accEthRewardsPerShare = farmInfo.accEthRewardsPerShare;
uint256 stakedTVL = getStakedTVL();
if (block.timestamp > farmInfo.lastRewardTimestamp && stakedTVL != 0) {
uint256 timeElapsed = block.timestamp.sub(
farmInfo.lastRewardTimestamp
);
uint256 koroReward = timeElapsed.mul(
getNumberOfKoroRewardsPerSecond(koroRewardAllocation)
);
uint256 ethReward = timeElapsed.mul(
getAmountOfEthRewardsPerSecond(ethRewardAllocation)
);
accKoroRewardsPerShare = accKoroRewardsPerShare.add(
koroReward.mul(precisionScaleUp).div(stakedTVL)
);
accEthRewardsPerShare = accEthRewardsPerShare.add(
ethReward.mul(precisionScaleUp).div(stakedTVL)
);
}
pendinKoroTokens = user
.amount
.mul(accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
pendingEthWei = user
.amount
.mul(accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
}
/**
* @notice Calculates and returns the TVL in USD staked in the farm
* @dev Uses the price of 1 Koromaru to calculate the TVL in USD
*/
function getStakedTVL() public view returns (uint256) {
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
uint256 totalLPsupply = koromaruUniV2.totalSupply();
return stakedLP.mul(getTVLUsingKoro()).div(totalLPsupply);
}
/**
* @notice Calculates and updates the farm's rewards per share
* @dev Called by other function to update the function state
*/
function updateFarm() public whenNotPaused returns (FarmInfo memory farm) {
farm = farmInfo;
uint256 WETHBalance = IERC20(WETHAddress).balanceOf(address(this));
if (WETHBalance > 0) IWETH(WETHAddress).withdraw(WETHBalance);
if (block.timestamp > farm.lastRewardTimestamp) {
uint256 stakedTVL = getStakedTVL();
if (stakedTVL > 0) {
uint256 timeElapsed = block.timestamp.sub(
farm.lastRewardTimestamp
);
uint256 koroReward = timeElapsed.mul(
getNumberOfKoroRewardsPerSecond(koroRewardAllocation)
);
uint256 ethReward = timeElapsed.mul(
getAmountOfEthRewardsPerSecond(ethRewardAllocation)
);
farm.accKoroRewardsPerShare = farm.accKoroRewardsPerShare.add(
(koroReward.mul(precisionScaleUp) / stakedTVL)
);
farm.accEthRewardsPerShare = farm.accEthRewardsPerShare.add(
(ethReward.mul(precisionScaleUp) / stakedTVL)
);
}
farm.lastRewardTimestamp = block.timestamp;
farmInfo = farm;
}
}
/**
* @notice Deposit Koromaru tokens into farm
* @dev Deposited Koromaru will zap into Koro/WETH LP tokens, a refund of TX fee % will be issued
*/
function depositKoroTokensOnly(uint256 _amount)
external
whenNotPaused
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid Koro Amount");
require(
_amount <= zapKoroLimit,
"KOROFARM: Can't deposit more than Zap Limit"
);
(uint256 lpZappedIn, , ) = ZapIn(_amount, false);
// do tax refund
userInfo[msg.sender].unpaidKoro += _amount.mul(taxRefundPercentage).div(
_1hundred_Percent
);
onDeposit(msg.sender, lpZappedIn);
}
/**
* @notice Deposit Koro/WETH LP tokens into farm
*/
function depositKoroLPTokensOnly(uint256 _amount)
external
whenNotPaused
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid KoroLP Amount");
koromaruUniV2.safeTransferFrom(msg.sender, address(this), _amount);
onDeposit(msg.sender, _amount);
}
/**
* @notice Deposit Koromaru, Koromaru/Eth LP and Eth at once into farm requires all 3
*/
function depositMultipleAssets(uint256 _koro, uint256 _koroLp)
external
payable
whenNotPaused
nonReentrant
{
// require(_koro > 0, "KOROFARM: Invalid Koro Amount");
// require(_koroLp > 0, "KOROFARM: Invalid LP Amount");
require(
_koro <= zapKoroLimit,
"KOROFARM: Can't deposit more than Zap Limit"
);
// execute the zap
// (uint256 lpZappedIn,uint256 wethBalance, uint256 korobalance)= ZapIn(_koro, true);
(uint256 lpZappedIn, , ) = msg.value > 0
? ZapIn(_koro, true)
: ZapIn(_koro, false);
// transfer the lp in
if (_koroLp > 0)
koromaruUniV2.safeTransferFrom(
address(msg.sender),
address(this),
_koroLp
);
uint256 sumOfLps = lpZappedIn + _koroLp;
// do tax refund
userInfo[msg.sender].unpaidKoro += _koro.mul(taxRefundPercentage).div(
_1hundred_Percent
);
onDeposit(msg.sender, sumOfLps);
}
/**
* @notice Deposit Eth only into farm
* @dev Deposited Eth will zap into Koro/WETH LP tokens
*/
function depositEthOnly() external payable whenNotPaused nonReentrant {
require(msg.value > 0, "KOROFARM: Invalid Eth Amount");
// (uint256 lpZappedIn, uint256 wethBalance, uint256 korobalance)= ZapIn(0, false);
(uint256 lpZappedIn, , ) = ZapIn(0, false);
onDeposit(msg.sender, lpZappedIn);
}
/**
* @notice Withdraw all staked LP tokens + rewards from farm. Only possilbe after harvest interval.
Use emergency withdraw if you want to withdraw before harvest interval. No rewards will be returned.
* @dev Farmer's can choose to get back LP tokens or Zap out to get Koromaru and Eth
*/
function withdraw(bool _useZapOut) external whenNotPaused nonReentrant {
uint256 balance = userInfo[msg.sender].amount;
require(balance > 0, "Withdraw: You have no balance");
updateFarm();
if (_useZapOut) {
zapLPOut(balance);
} else {
koromaruUniV2.transfer(msg.sender, balance);
}
onWithdraw(msg.sender);
emit Withdraw(msg.sender, balance);
}
/**
* @notice Harvest all rewards from farm
*/
function harvest() external whenNotPaused nonReentrant {
updateFarm();
harvestRewards(msg.sender);
}
/**
* @notice Compounds rewards from farm. Only available after harvest interval is reached for farmer.
*/
function compound() external whenNotPaused nonReentrant {
updateFarm();
UserInfo storage user = userInfo[msg.sender];
require(
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval,
"HarvestRewards: Not yet ripe"
);
uint256 koroCompounded;
uint256 ethCompounded;
uint256 pendinKoroTokens = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
uint256 pendingEthWei = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
{
uint256 koromaruBalance = koromaru.balanceOf(address(this));
if (pendinKoroTokens > 0) {
if (pendinKoroTokens > koromaruBalance) {
// not enough koro balance to reward farmer
user.unpaidKoro = pendinKoroTokens.sub(koromaruBalance);
totalKoroRewarded = totalKoroRewarded.add(koromaruBalance);
koroCompounded = koromaruBalance;
} else {
user.unpaidKoro = 0;
totalKoroRewarded = totalKoroRewarded.add(pendinKoroTokens);
koroCompounded = pendinKoroTokens;
}
}
}
{
uint256 ethBalance = getEthBalance();
if (pendingEthWei > ethBalance) {
// not enough Eth balance to reward farmer
user.unpaidEth = pendingEthWei.sub(ethBalance);
totalEthRewarded = totalEthRewarded.add(ethBalance);
IWETH(WETHAddress).deposit{value: ethBalance}();
ethCompounded = ethBalance;
} else {
user.unpaidEth = 0;
totalEthRewarded = totalEthRewarded.add(pendingEthWei);
IWETH(WETHAddress).deposit{value: pendingEthWei}();
ethCompounded = pendingEthWei;
}
}
(uint256 LP, , ) = _zapInMulti(koroCompounded, ethCompounded);
onCompound(msg.sender, LP);
emit Compound(msg.sender, koroCompounded, ethCompounded);
}
/**
* @notice Returns time in seconds to next harvest.
*/
function timeToHarvest(address _user)
public
view
whenNotPaused
returns (uint256)
{
UserInfo storage user = userInfo[_user];
if (
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval
) {
return 0;
}
return
user.lastRewardHarvestedTime.sub(
block.timestamp.sub(rewardHarvestingInterval)
);
}
/**
* @notice Withdraw all staked LP tokens without rewards.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
koromaruUniV2.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, user.amount);
userInfo[msg.sender] = UserInfo(0, 0, 0, 0, 0, 0);
}
//--------------- End Contract Farmer -------------------
//---------------- Contract Utils ----------------------
/**
* @notice Calculates the total amount of rewards per day in USD
* @dev The returned value is in USD * 1e18 (WETH decimals), actual USD value is calculated by dividing the value by 1e18
*/
function getUSDDailyRewards() public view whenNotPaused returns (uint256) {
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
uint256 totalLPsupply = koromaruUniV2.totalSupply();
uint256 stakedTVL = stakedLP.mul(getTVLUsingKoro()).div(totalLPsupply);
return APR.mul(stakedTVL).div(_1hundred_Percent);
}
/**
* @notice Calculates the total amount of rewards per second in USD
* @dev The returned value is in USD * 1e18 (WETH decimals), actual USD value is calculated by dividing the value by 1e18
*/
function getUSDRewardsPerSecond() internal view returns (uint256) {
// final return value should be divided by (1e18) (i.e WETH decimals) to get USD value
uint256 dailyRewards = getUSDDailyRewards();
return dailyRewards.div(secsPerDay);
}
/**
* @notice Calculates the total number of koromaru token rewards per second
* @dev The returned value must be divided by the koromaru token decimals to get the actual value
*/
function getNumberOfKoroRewardsPerSecond(uint256 _koroRewardAllocation)
internal
view
returns (uint256)
{
uint256 priceOfUintKoro = getLatestKoroPrice(); // 1e18
uint256 rewardsPerSecond = getUSDRewardsPerSecond(); // 1e18
return
rewardsPerSecond
.mul(_koroRewardAllocation)
.mul(koromaruDecimals)
.div(priceOfUintKoro)
.div(_1hundred_Percent); //to be div by koro decimals (i.e 1**(18-18+korodecimals)
}
/**
* @notice Calculates the total amount of Eth rewards per second
* @dev The returned value must be divided by the 1e18 to get the actual value
*/
function getAmountOfEthRewardsPerSecond(uint256 _ethRewardAllocation)
internal
view
returns (uint256)
{
uint256 priceOfUintEth = getLatestEthPrice(); // 1e8
uint256 rewardsPerSecond = getUSDRewardsPerSecond(); // 1e18
uint256 scaleUpToWei = 1e8;
return
rewardsPerSecond
.mul(_ethRewardAllocation)
.mul(scaleUpToWei)
.div(priceOfUintEth)
.div(_1hundred_Percent); // to be div by 1e18 (i.e 1**(18-8+8)
}
/**
* @notice Returns the rewards rate/second for both koromaru and eth
*/
function getRewardsPerSecond()
public
view
whenNotPaused
returns (uint256 koroRewards, uint256 ethRewards)
{
require(
koroRewardAllocation.add(ethRewardAllocation) == _1hundred_Percent,
"getRewardsPerSecond: Invalid reward allocation ratio"
);
koroRewards = getNumberOfKoroRewardsPerSecond(koroRewardAllocation);
ethRewards = getAmountOfEthRewardsPerSecond(ethRewardAllocation);
}
/**
* @notice Calculates and returns the TVL in USD (actaul TVL, not staked TVL)
* @dev Uses Eth price from price feed to calculate the TVL in USD
*/
function getTVL() public view returns (uint256 tvl) {
// final return value should be divided by (1e18) (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 TVLEth = 2 *
(address(token0) == address(koromaru) ? resv1 : resv0);
uint256 priceOfEth = getLatestEthPrice();
tvl = TVLEth.mul(priceOfEth).div(EthPriceFeedDecimal);
}
/**
* @notice Calculates and returns the TVL in USD (actaul TVL, not staked TVL)
* @dev Uses minimum Eth price in USD for 1 koromaru token to calculate the TVL in USD
*/
function getTVLUsingKoro() public view whenNotPaused returns (uint256 tvl) {
// returned value should be divided by (1e18) (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 TVLKoro = 2 *
(address(token0) == address(koromaru) ? resv0 : resv1);
uint256 priceOfKoro = getLatestKoroPrice();
tvl = TVLKoro.mul(priceOfKoro).div(koromaruDecimals);
}
/**
* @notice Get's the latest Eth price in USD
* @dev Uses ChainLink price feed to get the latest Eth price in USD
*/
function getLatestEthPrice() internal view returns (uint256) {
// final return value should be divided by 1e8 to get USD value
(, int256 price, , , ) = priceFeed.latestRoundData();
return uint256(price);
}
/**
* @notice Get's the latest Unit Koro price in USD
* @dev Uses estimated price per koromaru token in USD
*/
function getLatestKoroPrice() internal view returns (uint256) {
// returned value must be divided by 1e18 (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
bool isKoro = address(token0) == address(koromaru);
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 oneKoro = 1 * koromaruDecimals;
uint256 optimalWethAmount = uniswapRouter.getAmountOut(
oneKoro,
isKoro ? resv0 : resv1,
isKoro ? resv1 : resv0
); //uniswapRouter.quote(oneKoro, isKoro ? resv1 : resv0, isKoro ? resv0 : resv1);
uint256 priceOfEth = getLatestEthPrice();
return optimalWethAmount.mul(priceOfEth).div(EthPriceFeedDecimal);
}
function onDeposit(address _user, uint256 _amount) internal {
require(!reachedMaxLimit(), "KOROFARM: Farm is full");
UserInfo storage user = userInfo[_user];
updateFarm();
if (user.amount > 0) {
// record as unpaid
user.unpaidKoro = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
user.unpaidEth = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
}
user.amount = user.amount.add(_amount);
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
if (
(block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval) || (rewardHarvestingInterval == 0)
) {
user.lastRewardHarvestedTime = block.timestamp;
}
emit Deposit(_user, _amount);
}
function onWithdraw(address _user) internal {
harvestRewards(_user);
userInfo[msg.sender].amount = 0;
userInfo[msg.sender].koroDebt = 0;
userInfo[msg.sender].ethDebt = 0;
}
function onCompound(address _user, uint256 _amount) internal {
require(!reachedMaxLimit(), "KOROFARM: Farm is full");
UserInfo storage user = userInfo[_user];
user.amount = user.amount.add(_amount);
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
user.lastRewardHarvestedTime = block.timestamp;
}
function harvestRewards(address _user) internal {
UserInfo storage user = userInfo[_user];
require(
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval,
"HarvestRewards: Not yet ripe"
);
uint256 pendinKoroTokens = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
uint256 pendingEthWei = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
{
uint256 koromaruBalance = koromaru.balanceOf(address(this));
if (pendinKoroTokens > 0) {
if (pendinKoroTokens > koromaruBalance) {
// not enough koro balance to reward farmer
koromaru.safeTransfer(_user, koromaruBalance);
user.unpaidKoro = pendinKoroTokens.sub(koromaruBalance);
totalKoroRewarded = totalKoroRewarded.add(koromaruBalance);
emit KoroRewardsHarvested(_user, koromaruBalance);
} else {
koromaru.safeTransfer(_user, pendinKoroTokens);
user.unpaidKoro = 0;
totalKoroRewarded = totalKoroRewarded.add(pendinKoroTokens);
emit KoroRewardsHarvested(_user, pendinKoroTokens);
}
}
}
{
uint256 ethBalance = getEthBalance();
if (pendingEthWei > ethBalance) {
// not enough Eth balance to reward farmer
(bool sent, ) = _user.call{value: ethBalance}("");
require(sent, "Failed to send Ether");
user.unpaidEth = pendingEthWei.sub(ethBalance);
totalEthRewarded = totalEthRewarded.add(ethBalance);
emit EthRewardsHarvested(_user, ethBalance);
} else {
(bool sent, ) = _user.call{value: pendingEthWei}("");
require(sent, "Failed to send Ether");
user.unpaidEth = 0;
totalEthRewarded = totalEthRewarded.add(pendingEthWei);
emit EthRewardsHarvested(_user, pendingEthWei);
}
}
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
user.lastRewardHarvestedTime = block.timestamp;
}
/**
* @notice Convert's Koro LP tokens back to Koro and Eth
*/
function zapLPOut(uint256 _amount)
private
returns (uint256 _koroTokens, uint256 _ether)
{
(_koroTokens, _ether) = zapOut(_amount);
(bool sent, ) = msg.sender.call{value: _ether}("");
require(sent, "Failed to send Ether");
koromaru.safeTransfer(msg.sender, _koroTokens);
}
function getEthBalance() public view returns (uint256) {
return address(this).balance;
}
function getUserInfo(address _user)
public
view
returns (
uint256 amount,
uint256 stakedInUsd,
uint256 timeToHarves,
uint256 pendingKoro,
uint256 pendingEth
)
{
amount = userInfo[_user].amount;
timeToHarves = timeToHarvest(_user);
(pendingKoro, pendingEth) = getPendingRewards(_user);
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
stakedInUsd = stakedLP > 0
? userInfo[_user].amount.mul(getStakedTVL()).div(stakedLP)
: 0;
}
function getFarmInfo()
public
view
returns (
uint256 tvl,
uint256 totalStaked,
uint256 circSupply,
uint256 dailyROI,
uint256 ethDistribution,
uint256 koroDistribution
)
{
tvl = getStakedTVL();
totalStaked = koromaruUniV2.balanceOf(address(this));
circSupply = getCirculatingSupplyLocked();
dailyROI = APR;
ethDistribution = ethRewardAllocation;
koroDistribution = koroRewardAllocation;
}
function getCirculatingSupplyLocked() public view returns (uint256) {
address deadWallet = address(
0x000000000000000000000000000000000000dEaD
);
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 koroResv = address(token0) == address(koromaru) ? resv0 : resv1;
uint256 lpSupply = koromaruUniV2.totalSupply();
uint256 koroCirculatingSupply = koromaru.totalSupply().sub(
koromaru.balanceOf(deadWallet)
);
uint256 stakedLp = koromaruUniV2.balanceOf(address(this));
return
(stakedLp.mul(koroResv).mul(1e18).div(lpSupply)).div(
koroCirculatingSupply
); // divide by 1e18
}
function approveRouterIfNotApproved() private {
if (koromaru.allowance(address(this), address(uniswapRouter)) == 0) {
koromaru.safeApprove(address(uniswapRouter), type(uint256).max);
}
if (
koromaruUniV2.allowance(address(this), address(uniswapRouter)) == 0
) {
koromaruUniV2.approve(address(uniswapRouter), type(uint256).max);
}
}
function reachedMaxLimit() public view returns (bool) {
uint256 lockedLP = koromaruUniV2.balanceOf(address(this));
if (maxLPLimit < 1) return false; // unlimited
if (lockedLP >= maxLPLimit) return true;
return false;
}
//--------------- End Contract Utils -------------------
receive() external payable {
emit IncreaseEthRewardPool(msg.value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.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 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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 `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.0 (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 generally not needed starting with Solidity 0.8, since 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;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.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 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());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 v4.4.0 (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);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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;
}
}
| Reset's the chainLink price feed to the default price feed/ | function resetPriceFeed() external onlyOwner {
priceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
}
| 12,599,141 |
pragma solidity 0.4.26;
import './Owned.sol';
import './Utils.sol';
import './interfaces/IContractRegistry.sol';
/**
* @dev Base contract for ContractRegistry clients
*/
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_FEATURES = "ContractFeatures";
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
bytes32 internal constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory";
bytes32 internal constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant BANCOR_CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant BANCOR_CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
IContractRegistry public registry; // address of the current contract-registry
IContractRegistry public prevRegistry; // address of the previous contract-registry
bool public onlyOwnerCanUpdateRegistry; // only an owner can update the contract-registry
/**
* @dev verifies that the caller is mapped to the given contract name
*
* @param _contractName contract name
*/
modifier only(bytes32 _contractName) {
require(msg.sender == addressOf(_contractName));
_;
}
/**
* @dev initializes a new ContractRegistryClient instance
*
* @param _registry address of a contract-registry contract
*/
constructor(IContractRegistry _registry) internal validAddress(_registry) {
registry = IContractRegistry(_registry);
prevRegistry = IContractRegistry(_registry);
}
/**
* @dev updates to the new contract-registry
*/
function updateRegistry() public {
// verify that this function is permitted
require(msg.sender == owner || !onlyOwnerCanUpdateRegistry);
// get the new contract-registry
address newRegistry = addressOf(CONTRACT_REGISTRY);
// verify that the new contract-registry is different and not zero
require(newRegistry != address(registry) && newRegistry != address(0));
// verify that the new contract-registry is pointing to a non-zero contract-registry
require(IContractRegistry(newRegistry).addressOf(CONTRACT_REGISTRY) != address(0));
// save a backup of the current contract-registry before replacing it
prevRegistry = registry;
// replace the current contract-registry with the new contract-registry
registry = IContractRegistry(newRegistry);
}
/**
* @dev restores the previous contract-registry
*/
function restoreRegistry() public ownerOnly {
// restore the previous contract-registry
registry = prevRegistry;
}
/**
* @dev restricts the permission to update the contract-registry
*
* @param _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only
*/
function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) ownerOnly public {
// change the permission to update the contract-registry
onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
}
/**
* @dev returns the address associated with the given contract name
*
* @param _contractName contract name
*
* @return contract address
*/
function addressOf(bytes32 _contractName) internal view returns (address) {
return registry.addressOf(_contractName);
}
}
| restricts the permission to update the contract-registry _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only/ change the permission to update the contract-registry | function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) ownerOnly public {
onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
}
| 1,823,272 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
import "../../utils/TokenUtils.sol";
import "../ActionBase.sol";
import "./helpers/AaveV3Helper.sol";
/// @title Set positions eMode on Aave v3
contract AaveV3SetEMode is ActionBase, AaveV3Helper {
using TokenUtils for address;
struct Params {
uint8 categoryId;
bool useDefaultMarket;
address market;
}
/// @inheritdoc ActionBase
function executeAction(
bytes calldata _callData,
bytes32[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
Params memory params = parseInputs(_callData);
params.market = _parseParamAddr(params.market, _paramMapping[0], _subData, _returnValues);
(uint256 categoryId, bytes memory logData) = _setEmode(params.market, params.categoryId);
emit ActionEvent("AaveV3SetEMode", logData);
return bytes32(categoryId);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes calldata _callData) public payable override {
Params memory params = parseInputs(_callData);
(, bytes memory logData) = _setEmode(params.market, params.categoryId);
logger.logActionDirectEvent("AaveV3SetEMode", logData);
}
function executeActionDirectL2() public payable {
Params memory params = decodeInputs(msg.data[4:]);
(, bytes memory logData) = _setEmode(params.market, params.categoryId);
logger.logActionDirectEvent("AaveV3SetEMode", logData);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice User sets EMode for Aave position on Proxy
/// @param _market Address provider for specific market
/// @param _categoryId eMode category id (0 - 255)
function _setEmode(address _market, uint8 _categoryId)
internal
returns (uint256, bytes memory)
{
IPoolV3 lendingPool = getLendingPool(_market);
lendingPool.setUserEMode(_categoryId);
bytes memory logData = abi.encode(_market, _categoryId);
return (_categoryId, logData);
}
function parseInputs(bytes memory _callData) public pure returns (Params memory params) {
params = abi.decode(_callData, (Params));
if (params.useDefaultMarket) {
params.market = DEFAULT_AAVE_MARKET;
}
}
function encodeInputs(Params memory params) public pure returns (bytes memory encodedInput) {
encodedInput = bytes.concat(this.executeActionDirectL2.selector);
encodedInput = bytes.concat(encodedInput, bytes1(params.categoryId));
encodedInput = bytes.concat(encodedInput, boolToBytes(params.useDefaultMarket));
if (!params.useDefaultMarket) {
encodedInput = bytes.concat(encodedInput, bytes20(params.market));
}
}
function decodeInputs(bytes calldata encodedInput) public pure returns (Params memory params) {
params.categoryId = uint8(bytes1(encodedInput[0:1]));
params.useDefaultMarket = bytesToBool(bytes1(encodedInput[1:2]));
if (params.useDefaultMarket) {
params.market = DEFAULT_AAVE_MARKET;
} else {
params.market = address(bytes20(encodedInput[2:22]));
}
}
}
| @inheritdoc ActionBase | function executeActionDirect(bytes calldata _callData) public payable override {
Params memory params = parseInputs(_callData);
(, bytes memory logData) = _setEmode(params.market, params.categoryId);
logger.logActionDirectEvent("AaveV3SetEMode", logData);
}
| 7,295,064 |
./partial_match/1/0x1c075411c72789fA64843a35e453FA2B3Df4E380/sources/HodlDex.sol | configure access control join contracts | function init(address dexAddr) external initializer {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(DEX_ROLE, dexAddr);
dex = IDex(dexAddr);
token = new HTEthUsd();
initialized = true;
emit Configured(msg.sender, dexAddr, address(token));
}
| 4,398,138 |
./full_match/80001/0x1C4879B22e34BEE828eC448387c144251f50d409/sources/contracts/KOMPrivateSale.sol | Transfer amount ERC20 tokens from msg.sender to contract | function despoitERC20(uint256 _amount) external{
erc20Token.approve(msg.sender,_amount);
erc20Token.transferFrom(msg.sender, address(this), _amount);
}
| 876,359 |
./partial_match/1/0x2fDa6c41C4db721A92A7AbD15180e341EE0e1E0a/sources/PawUniLPStake.sol | Stop rewards, withdraw all reward Only callable by owner. Needs to be for emergency./ | function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
require(_amount <= rewardTreasure, "Exceed withdrawable amount");
wPAWToken.safeTransfer(address(msg.sender), _amount);
rewardTreasure = rewardTreasure - _amount;
_updatePool();
}
| 15,729,785 |
./partial_match/1/0x56b9BC878ce50e861540c8E977b4e45Fdc303dfF/sources/contracts/SoulSeasonTwo.sol | Toggle minting status | function setMintActive() external onlyOwner {
mintActive = !mintActive;
}
| 4,351,841 |
./partial_match/1/0x7d3CD037aE7efA9eBed7432c11c9DFa73519303d/sources/contracts/_external/ozproxy/ERC1967/ERC1967Upgrade.sol | Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). Emits a {BeaconUpgraded} event./ | function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
| 3,609,154 |
pragma solidity ^0.4.18;
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;
}
}
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
contract Auction {
struct Item {
address owner;
address winner;
uint finish_at;
uint start_price;
uint sale_price;
uint amount;
}
TokenDriver public driver;
ERC721 public erc721token;
ERC20 public izx;
address public host;
uint public host_share;
mapping(uint256 => Item) public items;
event Sale( address indexed token, address indexed owner, uint256 tokenId);
event Bid( address indexed token, address indexed bidder, uint256 tokenId, uint256 amount);
event Sold( address indexed token, address indexed winner, uint256 tokenId, uint256 amount);
using SafeMath for uint256;
/**
* @dev creates a new auction contract for ERC721 token
* @param _host The initiator of the auction creation. Typically it is a game owner or promoter
* @param _token The address of ERC721 token, traded in new auction
* @param _host_share Percentage (0 to 100) share of the payout for
* every completed auction sale in the new contract. If equal to 0, all bid is payed
* to the winner of the auction. If set to 100, all bid is payed to host, nothing left to bidder.
*/
function Auction( address _host, ERC721 _token, uint _host_share ) public {
require(address(_token) != address(0));
require(_host_share <= 100);
driver = TokenDriver(msg.sender);
izx = driver.token();
erc721token = _token;
host = _host;
host_share = _host_share;
}
/**
* @dev start a new round fo auction to sell ERC721 token for IZX
* @param _tokenId ERC721 token ID to be sold in auction.
* @param _start_price Minimum bid amount in IZX. Note, that IZX has 18 decimals.
* @param _sale_price Bid amount for immedeate sale close. Note, that IZX has 18 decimals.
* @param _duration duration in seconds, after which auction round is finished. After this, call withdraw method
* to get tokens.
*
* @notice Caller must be an owner of the ERC721 token ID and Caller must approve the token to this contract.
*/
function sell( uint _tokenId, uint _start_price, uint _sale_price, uint _duration) public {
require( msg.sender == erc721token.ownerOf(_tokenId) );
require( _sale_price >= _start_price );
require( _duration > 0 );
require( items[_tokenId].owner == address(0) );
items[_tokenId] = Item(msg.sender, address(0), now.add(_duration), _start_price, _sale_price, 0);
Sale( erc721token, msg.sender, _tokenId);
}
/**
* @dev make a bid to buy ERC721 token for IZX for specified amount of IZX
* @param _tokenId ERC721 token ID to be bought
* @param _amount IZX amount which in maximum caller wishes to pay.
*
* @notice Caller must own IZX tokens in this amount and must approve the spending to this contract.
* If _amount is larger than sale_price, then only sale_price is withdrawn from caller.
*/
function bid( uint _tokenId, uint _amount ) public {
Item storage item = items[_tokenId];
require( item.finish_at > now );
require( _amount > item.amount );
require( _amount >= item.start_price );
if( item.winner == address(0)){
erc721token.takeOwnership(_tokenId);
}else{
require(izx.transfer(item.winner, item.amount));
}
if( _amount >= item.sale_price ){
require(izx.transferFrom(msg.sender, this, item.sale_price));
close(_tokenId, item.owner, msg.sender, item.sale_price);
}else{
require(izx.transferFrom(msg.sender, this, _amount));
item.winner = msg.sender;
item.amount = _amount;
}
Bid( erc721token, msg.sender, _tokenId, _amount);
}
/**
* @dev withdraw ERC721 and IZX tokens after finish_at time of the auction
* @param _tokenId ERC721 token ID to be transfered
*/
function withdraw(uint _tokenId) public {
Item storage item = items[_tokenId];
require( now > item.finish_at );
require( item.amount > 0);
close(_tokenId, item.owner, item.winner, item.amount);
}
// --- INTERNAL METHODS ----
/**
* @dev closes the auction, transfers IZX and ERC721 token.
*
* @param _tokenId ERC721 token ID to be transfered to auction winner
* @param _owner is the seller address
* @param _winner is the buyer address
* @param _amount is the bid amount
*
* @notice this method called in 2 cases: after the finish_at by manual withdraw or by
* bid method, when amount is larger or equal to tsbid price.
*/
function close(uint _tokenId, address _owner, address _winner, uint _amount) internal {
uint host_amount = _amount.mul(host_share) / 100;
if(host_amount>0){
izx.transfer(host, host_amount);
}
uint owner_amount = _amount.sub(host_amount);
if(owner_amount>0){
izx.transfer(_owner, owner_amount);
}
erc721token.transfer(_winner, _tokenId);
delete items[_tokenId];
Sold( erc721token, _winner, _tokenId, _amount);
}
}
contract Campaign {
struct Prize {
address advertiser;
address winner;
uint expires_at;
}
TokenDriver public driver;
ERC721 public erc721token;
ERC20 public izx;
address public host;
uint public lifetime;
uint public token_price;
uint public winner_payout;
uint public host_payout;
mapping(uint256 => Prize) public prizes;
event Claimed( address indexed token, address indexed winner, address indexed advertiser, uint256 tokenId);
event Reclaimed( address indexed token, address indexed winner, address indexed advertiser, uint256 tokenId);
event Converted( address indexed token, address indexed winner, address indexed advertiser, uint256 tokenId);
using SafeMath for uint256;
/**
* @dev create a new advertising contract for ERC721 token
*
* @param _host The initiator of the campaign creation. Typically it is a game owner or promoter
* @param _token The address of ERC721 token, traded in new campaign
* @param _lifetime The time period in seconds, allowed to convert the prize
* after it is claimed by ERC721 token owner. I this time expires, and prize is not converted to IZX tokens,
* the token can be returned to the initial owner.
* @param _token_price Price of every ERC721 token in IZX, payed by advertiser.
* @param _host_share Percentage (0 to 100) share of the payout for
* every completed conversion in the new contract. If equal to 0, all token price is payed
* to the winner of the prize. If set to 100, all bid is payed to host, nothing left to the winner.
*/
function Campaign( address _host,
ERC721 _token,
uint _lifetime,
uint _token_price,
uint _host_share) public {
require(address(_token) != address(0));
require(_lifetime > 0);
require(_token_price > 0);
require(_host_share <= 100);
driver = TokenDriver(msg.sender);
izx = driver.token();
erc721token = _token;
host = _host;
lifetime = _lifetime;
token_price = _token_price;
host_payout = _host_share.mul(token_price) / 100;
winner_payout = _token_price.sub(host_payout);
}
/**
* @dev player claims owing the ERC721 token
*
* @param _tokenId ID of owned ERC721 token in the game
* @param _advertiser The address of advertiser, who is assumed to convert this token
*
* @notice player must call ERC721 approve method to allow this contract to take ownershio of the token,
* effectively reserving it for conversion. Also, the token price in IZX is reserved from advertiser account.
*/
function claim(uint _tokenId, address _advertiser) public {
require(msg.sender == erc721token.ownerOf(_tokenId));
require(izx.transferFrom(_advertiser, this, token_price));
erc721token.takeOwnership(_tokenId);
prizes[_tokenId] = Prize(_advertiser, msg.sender, now.add(lifetime) );
Claimed(erc721token, msg.sender, _advertiser, _tokenId);
}
/**
* @dev action, opposite to claim. Player, who claimed the token can call this before convert,
* or anybody can call this after prize is expired.
*
* @param _tokenId ID of claimed ERC721 token
*
* @notice player get his ERC721 back, and advertiser receives token price IZX amount.
* This transaction reverts claim transaction.
*/
function reclaim(uint _tokenId) public {
Prize storage prize = prizes[_tokenId];
require( (prize.winner == msg.sender) || (now > prize.expires_at) );
address advertiser = prize.advertiser;
address winner = prize.winner;
erc721token.transfer(prize.winner, _tokenId);
require(izx.transfer(advertiser, token_price));
delete prizes[_tokenId];
Reclaimed( erc721token, winner, advertiser, _tokenId);
}
/**
* @dev advertiser calls this method to approve IZX payout to player and host.
*
* @param _tokenId ID of claimed ERC721 token
*
* @notice payout distribution depends on host_share percentage.If equal to 0, all token price is payed
* to the player, claiming the prize. If set to 100, all bid is payed to host, nothing left to the player.
* On success, ERC721 token is transfered to advertiser, which he can burn or sell in auction, or put back to game
* on his will.
*/
function convert(uint _tokenId) public {
Prize storage prize = prizes[_tokenId];
require(prize.advertiser == msg.sender);
address winner = prize.winner;
erc721token.transfer(prize.advertiser, _tokenId);
if(winner_payout>0){
require(izx.transfer(winner, winner_payout));
}
if(host_payout>0){
require(izx.transfer(host, host_payout));
}
delete prizes[_tokenId];
Converted( erc721token, winner, msg.sender, _tokenId);
}
}
contract ControlledByVote {
ERC20 public token;
uint public min_voting_duration;
uint public max_voting_duration;
ControlledByVote public candidate;
uint public finishes_at;
bool public voices_counted;
bool public candidate_wins;
event VotingStarted( address indexed candidate, address indexed token, uint finishes_at);
event VotingCompleted( address indexed candidate, address indexed token, bool candidate_wins, uint voices_pro, uint voices_cons);
using SafeMath for uint256;
modifier onlyNoVoting() {
if(address(candidate) != address(0)){
require(now > finishes_at);
require(voices_counted);
require(!candidate_wins);
}
_;
}
modifier onlyVotedFor(ControlledByVote _vote_for) {
require(candidate != address(0));
require(candidate == _vote_for);
require(now > finishes_at);
require(voices_counted);
require(candidate_wins);
_;
}
function ControlledByVote( ERC20 _token, uint _min_voting_duration, uint _max_voting_duration ) public {
require( address(_token) != address(0));
require( _max_voting_duration >= _min_voting_duration);
require( _max_voting_duration > 0 );
token = _token;
min_voting_duration = _min_voting_duration;
max_voting_duration = _max_voting_duration;
}
function startVoting(ControlledByVote _candidate, uint _finishes_at) onlyNoVoting public {
require(address(_candidate) != address(0));
require(_candidate.token() == token);
require(_finishes_at >= now.add(min_voting_duration));
require(_finishes_at <= now.add(max_voting_duration));
candidate = _candidate;
finishes_at = _finishes_at;
voices_counted = false;
VotingStarted( candidate, token, finishes_at);
}
function finishVoting() public {
require(address(candidate) != address(0));
require(now > finishes_at);
require(!voices_counted);
uint voices_cons = token.balanceOf(this);
uint voices_pro = token.balanceOf(candidate);
candidate_wins = voices_pro > voices_cons;
voices_counted = true;
VotingCompleted( candidate, token, candidate_wins, voices_pro, voices_cons);
}
function votingInProgress() public view returns(bool){
return candidate!=address(0) && (now <= finishes_at);
}
}
contract ERC20 {
function balanceOf(address who) constant public returns (uint);
function allowance(address owner, address spender) constant public returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transferFrom(address from, address to, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract TokenController {
/// @notice Called when `_owner` sends ether to the 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) payable public 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 TokenDriver is TokenController, ControlledByVote {
event NewAuction( address indexed token, address indexed auction);
event NewCampaign( address indexed token, address indexed campaign);
event NewTokenDriver( address indexed token, address indexed new_driver);
mapping(address => bool) public allowed_contracts;
mapping(address => uint) public deposits;
using SafeMath for uint256;
/**
* @dev Throws if called by any account other than the token.
*/
modifier onlyToken() {
require(msg.sender == address(token));
_;
}
modifier onlyTokenOrController() {
require(msg.sender == address(token) || msg.sender == address(ControlledToken(token).controller() ) );
_;
}
function TokenDriver( ERC20 _token, uint _min_voting_duration, uint _max_voting_duration ) public
ControlledByVote(_token, _min_voting_duration, _max_voting_duration) {}
/**
* @dev creates a new auction contract for ERC721 token
* @param _token The address of ERC721 token, traded in new auction
* @param _host_share Percentage (0 to 100) share of the payout for
* every completed auction sale in the new contract. If equal to 0, all bid is payed
* to the winner of the auction. If set to 100, all bid is payed to host, nothing left to bidder.
*/
function createAuction(ERC721 _token, uint _host_share) external{
Auction auction = new Auction(msg.sender, _token, _host_share);
allowed_contracts[address(auction)] = true;
NewAuction( _token, auction);
}
/**
* @dev create a new advertising contract for ERC721 token
* @param _token The address of ERC721 token, traded in new campaign
* @param _lifetime The time period in seconds, allowed to convert the prize
* after it is claimed by ERC721 token owner. I this time expires, and prize is not converted to IZX tokens,
* the token can be returned to the initial owner.
* @param _token_price Price of every ERC721 token in IZX, payed by advertiser.
* @param _host_share Percentage (0 to 100) share of the payout for
* every completed conversion in the new contract. If equal to 0, all token price is payed
* to the winner of the prize. If set to 100, all bid is payed to host, nothing left to the winner.
*/
function createCampaign(ERC721 _token, uint _lifetime, uint _token_price, uint _host_share) external{
Campaign campaign = new Campaign(msg.sender, _token, _lifetime, _token_price, _host_share);
allowed_contracts[address(campaign)] = true;
NewCampaign( _token, campaign);
}
/// ----- METHODS IMPLEMENTATION FROM TokenController interface ----- ///
/// @notice Called when `_owner` sends ether to the Token contract
function proxyPayment(address) payable public onlyToken returns(bool){
return false;
}
/// @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 onlyToken returns(bool){
if( (_to==address(this) || _to==address(candidate)) && votingInProgress()){
TokenDriver(_to).register_deposit(_from, _amount);
return true;
}else{
return !isContract(_to) || allowed_contracts[_to];
}
}
/// @notice Notifies the controller about an approval allowing the
function onApprove(address, address _spender, uint) public onlyToken returns(bool){
return !isContract(_spender) || allowed_contracts[_spender] || _spender==address(this);
}
/// @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;
}
function register_deposit(address _from, uint _amount) onlyTokenOrController public {
deposits[_from] = deposits[_from].add(_amount);
}
function withdraw() public {
uint amount = deposits[msg.sender];
require(amount > 0);
deposits[msg.sender] = 0;
token.transfer(msg.sender, amount);
}
function changeController(ControlledByVote _newController) onlyVotedFor(_newController) public {
ControlledToken(token).changeController(_newController);
NewTokenDriver( token, address(_newController));
}
}
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) onlyController public {
controller = _newController;
}
}
contract ControlledToken is ERC20, Controlled {
uint256 constant MAX_UINT256 = 2**256 - 1;
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = '1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
uint256 public totalSupply;
function ControlledToken(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value);
if (isContract(controller)) {
require(TokenController(controller).onTransfer(msg.sender, _to, _value));
}
balances[msg.sender] -= _value;
balances[_to] += _value;
// Alerts the token controller of the transfer
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _value));
}
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _value));
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
////////////////
// 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 ) onlyController returns (bool) {
uint curTotalSupply = totalSupply;
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
totalSupply = curTotalSupply + _amount;
balances[_owner] = previousBalanceTo + _amount;
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 returns (bool) {
uint curTotalSupply = totalSupply;
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
totalSupply = curTotalSupply - _amount;
balances[_owner] = previousBalanceFrom - _amount;
Transfer(_owner, 0, _amount);
return true;
}
/// @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 () payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
/// @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;
}
/// @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) onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
ControlledToken token = ControlledToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
| Burns `_amount` tokens from `_owner` _owner The address that will lose the tokens _amount The quantity of tokens to burn return True if the tokens are burned correctly | function destroyTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply;
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
totalSupply = curTotalSupply - _amount;
balances[_owner] = previousBalanceFrom - _amount;
Transfer(_owner, 0, _amount);
return true;
}
| 7,313,639 |
./full_match/1287/0x8162876a0bD2bE9d48a2023d20d5955d51eC055D/sources/contracts/PartsStore.sol | Adds a new class to the list of available classes. part The class to add. Only the contract owner can call this function. Throws an error if the number of classes is already at the maximum (255)./ | function addClass(ImagePart calldata part) external onlyOwner onlyUnlocked {
classes.push(part);
}
| 7,097,285 |
./partial_match/8453/0xc7b006f084Ca79334DB41fE216D3195870FAc026/sources/DUCKRouter.sol | ADD LIQUIDITY create the pair if it doesn't exist yet | function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
if (IDUCKFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IDUCKFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = DUCKLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
uint amountBOptimal = DUCKLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'DUCKRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
uint amountAOptimal = DUCKLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'DUCKRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
| 16,760,453 |
./partial_match/1/0x373ae78a14577682591E088F2E78EF1417612c68/sources/contracts/mock/MockUniswapV2Router02.sol | performs chained getAmountIn calculations on any number of pairs | function getAmountsIn(
address factory,
uint amountOut,
address[] memory path
) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'MockUniswapV2Router02UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
| 4,169,202 |
./partial_match/1/0x927841445339777b644A26B75899F103C93FbBD7/sources/Staking.sol | Returns the sPLAY index, which tracks rebase growth return index_ Index of sPLAY | function index() public view returns (uint256 index_) {
return sPLAY.index();
}
| 4,444,408 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "./interfaces/IERC998TopDown.sol";
import "./interfaces/IERC998TopDownEnumerable.sol";
import "@openzeppelin/contracts/interfaces/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
interface IERC998ERC721BottomUp {
function transferToParent(
address _from,
address _toContract,
uint256 _toTokenId,
uint256 _tokenId,
bytes calldata _data
) external;
}
contract ERC998 is
IERC998ERC721TopDown,
ERC165,
IERC998ERC721TopDownEnumerable,
ERC721,
ERC721Enumerable,
ERC721URIStorage,
Pausable,
Ownable,
ERC721Burnable
{
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {}
// tokenId => token owner
mapping(uint256 => address) internal tokenIdToTokenOwner;
// root token owner address => (tokenId => approved address)
mapping(address => mapping(uint256 => address))
internal rootOwnerAndTokenIdToApprovedAddress;
// token owner => (operator address => bool)
mapping(address => mapping(address => bool)) internal tokenOwnerToOperators;
// tokenId => child contract
mapping(uint256 => address[]) private childContracts;
// tokenId => (child address => contract index+1)
mapping(uint256 => mapping(address => uint256)) private childContractIndex;
// tokenId => (child address => array of child tokens)
mapping(uint256 => mapping(address => uint256[])) private childTokens;
// tokenId => (child address => (child token => child index+1)
mapping(uint256 => mapping(address => mapping(uint256 => uint256)))
private childTokenIndex;
// token owner address => token count
mapping(address => uint256) internal tokenOwnerToTokenCount;
// child address => childId => tokenId
mapping(address => mapping(uint256 => uint256)) internal childTokenOwner;
// return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^
// this.tokenOwnerOf.selector ^ this.ownerOfChild.selector;
bytes32 public constant ERC998_MAGIC_VALUE =
0x00000000000000000000000000000000000000000000000000000000cd740db5;
//from zepellin ERC721Receiver.sol
//old version
bytes4 public constant ERC721_RECEIVED_OLD = 0xf0b9e5ba;
//new version
bytes4 public constant ERC721_RECEIVED_NEW = 0x150b7a02;
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
event parentNftMinted(uint256 indexed tokenId, address indexed to);
event childNftMinted(uint256 indexed tokenId, address indexed to);
function mintParent(address _to, string memory _ipfsUri)
internal
returns (uint256)
{
uint256 tokenId = _tokenIdCounter.current();
//mint token
_safeMint(_to, tokenId);
_setTokenURI(tokenId, _ipfsUri);
//update parent mappings
tokenIdToTokenOwner[tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
//increment counter
_tokenIdCounter.increment();
emit parentNftMinted(tokenId, address(_to));
return tokenId;
}
//mintChild is still a work in progress don't use yet.
function mintChild(uint256 _parentId, string calldata _ipfsUri)
public
returns (uint256)
{
uint256 tokenId = _tokenIdCounter.current();
address rootOwner = tokenIdToTokenOwner[_parentId];
console.log("tokenId", tokenId, "Root Owner", rootOwner);
//mint token
_safeMint(rootOwner, tokenId);
_setTokenURI(tokenId, _ipfsUri);
//update mappings
childContracts[_parentId].push(address(this));
tokenIdToTokenOwner[tokenId] = rootOwner;
childContractIndex[tokenId][address(this)]++;
childTokenIndex[_parentId][address(this)][tokenId]++;
childTokenOwner[address(this)][tokenId] = _parentId;
childTokens[_parentId][address(this)].push(tokenId);
tokenOwnerToTokenCount[rootOwner]++;
_tokenIdCounter.increment();
emit childNftMinted(tokenId, address(rootOwner));
return tokenId;
}
function convertBytes32ToAddress(bytes32 root)
public
pure
returns (address)
{
return address(uint160(uint256(root)));
}
function convertAddressToUint(address a) internal pure returns (uint256) {
return uint256(uint160(a));
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
}
// function addToPortfolio() {
// uint256 tokenId = 6;
// bytes memory tokenIdBytes = new bytes(32);
// assembly { mstore(add(tokenIdBytes, 32), tokenId) }
// safeTransferFrom(msg.sender, address(), 3, tokenIdBytes);
// }
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, ERC165)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
// returns the owner at the top of the tree of composables
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(
add(tempBytes, lengthmod),
mul(0x20, iszero(lengthmod))
)
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(
add(
add(_bytes, lengthmod),
mul(0x20, iszero(lengthmod))
),
_start
)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes32 _bytes, uint256 _start)
internal
pure
returns (address)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(
mload(add(add(_bytes, 0x20), _start)),
0x1000000000000000000000000
)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start)
internal
pure
returns (uint24)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3, "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
////////////////////////////////////////////////////////
// ERC721 implementation
////////////////////////////////////////////////////////
function rootOwnerOf(uint256 _tokenId)
public
view
override
returns (bytes32 rootOwner)
{
return rootOwnerOfChild(address(0), _tokenId);
}
function addressOfRootOwner(address _childContract, uint256 _childTokenId)
public
view
returns (address)
{
bytes32 data = rootOwnerOfChild(_childContract, _childTokenId);
return convertBytes32ToAddress(data);
}
// returns the owner at the top of the tree of composables
// Use Cases handled:
// Case 1: Token owner is this contract and token.
// Case 2: Token owner is other top-down composable
// Case 3: Token owner is other contract
// Case 4: Token owner is user
function rootOwnerOfChild(address _childContract, uint256 _childTokenId)
public
view
override
returns (bytes32 rootOwner)
{
address rootOwnerAddress;
if (_childContract != address(0)) {
(rootOwnerAddress, _childTokenId) = _ownerOfChild(
_childContract,
_childTokenId
);
} else {
rootOwnerAddress = tokenIdToTokenOwner[_childTokenId];
}
// Case 1: Token owner is this contract and token.
while (rootOwnerAddress == address(this)) {
(rootOwnerAddress, _childTokenId) = _ownerOfChild(
rootOwnerAddress,
_childTokenId
);
}
(bool callSuccess, bytes memory data) = rootOwnerAddress.staticcall(
abi.encodeWithSelector(0xed81cdda, address(this), _childTokenId)
);
if (data.length != 0) {
rootOwner = abi.decode(data, (bytes32));
}
if (callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
// Case 2: Token owner is other top-down composable
return rootOwner;
} else {
// Case 3: Token owner is other contract
// Or
// Case 4: Token owner is user
uint256 rootOwnerInt = convertAddressToUint(rootOwnerAddress);
return (ERC998_MAGIC_VALUE << 224) | bytes32(rootOwnerInt);
}
}
function ownerOf(uint256 _tokenId)
public
view
override
returns (address tokenOwner)
{
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0), "token owned by zero address");
return tokenOwner;
}
function balanceOf(address _tokenOwner)
public
view
override
returns (uint256)
{
require(_tokenOwner != address(0), "not owned");
return tokenOwnerToTokenCount[_tokenOwner];
}
function approve(address _approved, uint256 _tokenId) public override {
address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId))));
require(
rootOwner == msg.sender ||
tokenOwnerToOperators[rootOwner][msg.sender],
"You cannot approve this."
);
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved;
emit Approval(rootOwner, _approved, _tokenId);
}
function getApproved(uint256 _tokenId)
public
view
override
returns (address)
{
address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId))));
return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
function setApprovalForAll(address _operator, bool _approved)
public
override
{
require(_operator != address(0), "token not owned");
tokenOwnerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool)
{
require(_owner != address(0), "token not owned");
require(_operator != address(0), "no operator");
return tokenOwnerToOperators[_owner][_operator];
}
//_from is the current owner address, _to will be the tokenId of the token you want to tranfer ownership to OR the wallet to tranfer to, _tokenId is the token you will be transfering
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
) private {
require(_from != address(0), "also not");
require(
tokenIdToTokenOwner[_tokenId] == _from,
"token cannot be owned by sender"
);
require(_to != address(0), "not from dead address");
if (msg.sender != _from) {
(bool callSuccess, bytes memory data) = _from.staticcall(
abi.encodeWithSelector(0xed81cdda, address(this), _tokenId)
);
bytes32 rootOwner = abi.decode(data, (bytes32));
if (callSuccess == true) {
require(
rootOwner >> 224 != ERC998_MAGIC_VALUE,
"This child already has a parent."
);
}
require(
tokenOwnerToOperators[_from][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId] ==
msg.sender,
"You are not approved."
);
}
// clear approval
if (
rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId] != address(0)
) {
delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId];
emit Approval(_from, address(0), _tokenId);
}
// remove and transfer token
if (_from != _to) {
assert(tokenOwnerToTokenCount[_from] > 0);
tokenOwnerToTokenCount[_from]--;
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
}
emit Transfer(_from, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public override {
_transferFrom(_from, _to, _tokenId);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
) public override {
_transferFrom(_from, _to, _tokenId);
if (isContract(_to)) {
bytes4 retval = IERC721Receiver(_to).onERC721Received(
msg.sender,
_from,
_tokenId,
""
);
require(retval == ERC721_RECEIVED_OLD, "retval invalid");
}
}
//_from = address that owns parent nft, _to = address that minted the child nft, _tokenId = childNft ID, _data = parent NFT ID
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
) public override {
_transferFrom(_from, _to, _tokenId);
if (isContract(_to)) {
bytes4 retval = IERC721Receiver(_to).onERC721Received(
msg.sender,
_from,
_tokenId,
_data
);
require(
retval == ERC721_RECEIVED_OLD || retval == ERC721_RECEIVED_NEW,
"incorrect retval"
);
}
}
////////////////////////////////////////////////////////
// ERC998ERC721 and ERC998ERC721Enumerable implementation
////////////////////////////////////////////////////////
// tokenId of composable, mapped to child contract address
// child contract address mapped to child tokenId or amount
mapping(uint256 => mapping(address => uint256)) children;
// add ERC-721 children by tokenId
// @requires owner to approve transfer from this contract
// call _childContract.approve(this, _childTokenId)
// where this is the address of the parent token contract
/////////////////////WIP////////////////////////////////
// function addChild(
// uint256 _tokenId,
// address _childContract,
// uint256 _childTokenId
// ) public returns (bytes32) {
// // call the transfer function of the child contract
// // if approve was called using the address of this contract
// // _childTokenId will be transferred to this contract
// (bool callSuccess, bytes memory data) = _childContract.staticcall(
// abi.encode(
// bytes4(keccak256("transferFrom(address,address,uint256)")),
// msg.sender,
// this,
// _childTokenId
// )
// );
// require(callSuccess, "call failed");
// // if successful, add children to the mapping
// children[_tokenId][_childContract] = _childTokenId;
// //transfer token
// }
////////////////////////////WIP///////////////////////////
function removeChild(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) private {
uint256 tokenIndex = childTokenIndex[_tokenId][_childContract][
_childTokenId
];
require(tokenIndex != 0, "this token is not a child token.");
// remove child token
uint256 lastTokenIndex = childTokens[_tokenId][_childContract].length -
1;
uint256 lastToken = childTokens[_tokenId][_childContract][
lastTokenIndex
];
if (_childTokenId == lastToken) {
childTokens[_tokenId][_childContract][tokenIndex - 1] = lastToken;
childTokenIndex[_tokenId][_childContract][lastToken] = tokenIndex;
}
uint256 totalTokens = childTokens[_tokenId][_childContract].length;
if (totalTokens - 1 == 0) {
delete childTokens[_tokenId][_childContract];
} else {
delete childTokens[_tokenId][_childContract][totalTokens - 1];
}
delete childTokenIndex[_tokenId][_childContract][_childTokenId];
delete childTokenOwner[_childContract][_childTokenId];
// remove contract
if (lastTokenIndex == 0) {
uint256 lastContractIndex = childContracts[_tokenId].length - 1;
address lastContract = childContracts[_tokenId][lastContractIndex];
if (_childContract != lastContract) {
uint256 contractIndex = childContractIndex[_tokenId][
_childContract
];
childContracts[_tokenId][contractIndex] = lastContract;
childContractIndex[_tokenId][lastContract] = contractIndex;
}
delete childContracts[_tokenId];
delete childContractIndex[_tokenId][_childContract];
}
}
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external override {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
require(
tokenId > 0 ||
childTokenIndex[tokenId][_childContract][_childTokenId] > 0,
"not a child token"
);
require(tokenId == _fromTokenId, "cannot send to same token");
require(_to != address(0), "token owned by zero address");
address rootOwner = address(uint160(uint256(rootOwnerOf(tokenId))));
require(
rootOwner == msg.sender ||
tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] ==
msg.sender,
"you are not approved."
);
removeChild(tokenId, _childContract, _childTokenId);
IERC721(_childContract).safeTransferFrom(
address(this),
_to,
_childTokenId
);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId,
bytes calldata _data
) external override {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
require(
tokenId > 0 ||
childTokenIndex[tokenId][_childContract][_childTokenId] > 0,
"not a child token"
);
require(tokenId == _fromTokenId);
require(_to != address(0));
address rootOwner = address(uint160(uint256(rootOwnerOf(tokenId))));
require(
rootOwner == msg.sender ||
tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] ==
msg.sender,
"you are not approved."
);
removeChild(tokenId, _childContract, _childTokenId);
IERC721(_childContract).safeTransferFrom(
address(this),
_to,
_childTokenId,
_data
);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function transferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external override {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
require(
tokenId > 0 ||
childTokenIndex[tokenId][_childContract][_childTokenId] > 0,
"can only transfer child tokens"
);
require(tokenId == _fromTokenId, "cannot send same token");
require(_to != address(0), "don't burn this.");
address rootOwner = address(uint160(uint256(rootOwnerOf(tokenId))));
require(
rootOwner == msg.sender ||
tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] ==
msg.sender,
"you are not approved"
);
removeChild(tokenId, _childContract, _childTokenId);
//this is here to be compatible with cryptokitties and other old contracts that require being owner and approved
// before transferring.
//does not work with current standard which does not allow approving self, so we must let it fail in that case.
//0x095ea7b3 == "approve(address,uint256)"
(bool success, bytes memory data) = _childContract.call(
abi.encodeWithSelector(0x095ea7b3, this, _childTokenId)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"failed to approve"
);
IERC721(_childContract).transferFrom(address(this), _to, _childTokenId);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function transferChildToParent(
uint256 _fromTokenId,
address _toContract,
uint256 _toTokenId,
address _childContract,
uint256 _childTokenId,
bytes calldata _data
) external override {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
require(
tokenId > 0 ||
childTokenIndex[tokenId][_childContract][_childTokenId] > 0,
"not a child token"
);
require(tokenId == _fromTokenId, "token can't send itself");
require(_toContract != address(0), "don't burn this");
address rootOwner = address(uint160(uint256(rootOwnerOf(tokenId))));
require(
rootOwner == msg.sender ||
tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] ==
msg.sender,
"you are not approved"
);
removeChild(_fromTokenId, _childContract, _childTokenId);
IERC998ERC721BottomUp(_childContract).transferToParent(
address(this),
_toContract,
_toTokenId,
_childTokenId,
_data
);
emit TransferChild(
_fromTokenId,
_toContract,
_childContract,
_childTokenId
);
}
// this contract has to be approved first in _childContract
function getChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) external override {
receiveChild(_from, _tokenId, _childContract, _childTokenId);
require(
_from == msg.sender ||
IERC721(_childContract).isApprovedForAll(_from, msg.sender) ||
IERC721(_childContract).getApproved(_childTokenId) ==
msg.sender,
"you are not approved"
);
IERC721(_childContract).transferFrom(
_from,
address(this),
_childTokenId
);
}
function onERC721Received(
address _from,
uint256 _childTokenId,
bytes calldata _data
) external returns (bytes4) {
require(_data.length > 0, "no token id.");
// convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if (_data.length < 32) {
tokenId = tokenId >> (256 - _data.length * 8);
}
receiveChild(_from, tokenId, msg.sender, _childTokenId);
require(
IERC721(msg.sender).ownerOf(_childTokenId) != address(0),
"Child token not owned."
);
return ERC721_RECEIVED_OLD;
}
function onERC721Received(
address _operator,
address _from,
uint256 _childTokenId,
bytes calldata _data
) external override returns (bytes4) {
require(_data.length > 0, "parent not found");
// convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId;
assembly {
tokenId := calldataload(164)
}
if (_data.length < 32) {
tokenId = tokenId >> (256 - _data.length * 8);
}
receiveChild(_from, tokenId, msg.sender, _childTokenId);
require(
IERC721(msg.sender).ownerOf(_childTokenId) != address(0),
"Child token not owned."
);
return ERC721_RECEIVED_NEW;
}
function receiveChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) private {
require(
tokenIdToTokenOwner[_tokenId] != address(0),
"_tokenId does not exist."
);
require(
childTokenIndex[_tokenId][_childContract][_childTokenId] == 0,
"no child token sent."
);
uint256 childTokensLength = childTokens[_tokenId][_childContract]
.length;
if (childTokensLength == 0) {
childContractIndex[_tokenId][_childContract] = childContracts[
_tokenId
].length;
childContracts[_tokenId].push(_childContract);
}
childTokens[_tokenId][_childContract].push(_childTokenId);
childTokenIndex[_tokenId][_childContract][_childTokenId] =
childTokensLength +
1;
childTokenOwner[_childContract][_childTokenId] = _tokenId;
emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId);
}
function _ownerOfChild(address _childContract, uint256 _childTokenId)
internal
view
returns (address parentTokenOwner, uint256 parentTokenId)
{
parentTokenId = childTokenOwner[_childContract][_childTokenId];
require(
parentTokenId > 0 ||
childTokenIndex[parentTokenId][_childContract][_childTokenId] >
0,
"not a child"
);
return (tokenIdToTokenOwner[parentTokenId], parentTokenId);
}
function ownerOfChild(address _childContract, uint256 _childTokenId)
external
view
override
returns (bytes32 parentTokenOwner, uint256 parentTokenId)
{
parentTokenId = childTokenOwner[_childContract][_childTokenId];
require(
parentTokenId > 0 ||
childTokenIndex[parentTokenId][_childContract][_childTokenId] >
0,
"not a child"
);
uint256 tokenIdOwnerInt = convertAddressToUint(
tokenIdToTokenOwner[parentTokenId]
);
return (
(ERC998_MAGIC_VALUE << 224) | bytes32(tokenIdOwnerInt),
parentTokenId
);
}
function childExists(address _childContract, uint256 _childTokenId)
external
view
returns (bool)
{
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
return childTokenIndex[tokenId][_childContract][_childTokenId] != 0;
}
function totalChildContracts(uint256 _tokenId)
external
view
override
returns (uint256)
{
return childContracts[_tokenId].length;
}
function childContractByIndex(uint256 _tokenId, uint256 _index)
external
view
override
returns (address childContract)
{
require(_index < childContracts[_tokenId].length, "wrong index");
return childContracts[_tokenId][_index];
}
function totalChildTokens(uint256 _tokenId, address _childContract)
external
view
override
returns (uint256)
{
return childTokens[_tokenId][_childContract].length;
}
function childTokenByIndex(
uint256 _tokenId,
address _childContract,
uint256 _index
) external view override returns (uint256 childTokenId) {
require(
_index < childTokens[_tokenId][_childContract].length,
"wrong index."
);
return childTokens[_tokenId][_childContract][_index];
}
function allChildTokenIDs(
uint256 _tokenId,
address _childContract
) external view returns (uint256[] memory childTokenId) {
return childTokens[_tokenId][_childContract];
}
}
| returns the owner at the top of the tree of composables Use Cases handled: Case 1: Token owner is this contract and token. Case 2: Token owner is other top-down composable Case 3: Token owner is other contract Case 4: Token owner is user Case 1: Token owner is this contract and token. Case 2: Token owner is other top-down composable Case 3: Token owner is other contract Or Case 4: Token owner is user | function rootOwnerOfChild(address _childContract, uint256 _childTokenId)
public
view
override
returns (bytes32 rootOwner)
{
address rootOwnerAddress;
if (_childContract != address(0)) {
(rootOwnerAddress, _childTokenId) = _ownerOfChild(
_childContract,
_childTokenId
);
rootOwnerAddress = tokenIdToTokenOwner[_childTokenId];
}
while (rootOwnerAddress == address(this)) {
(rootOwnerAddress, _childTokenId) = _ownerOfChild(
rootOwnerAddress,
_childTokenId
);
}
(bool callSuccess, bytes memory data) = rootOwnerAddress.staticcall(
abi.encodeWithSelector(0xed81cdda, address(this), _childTokenId)
);
if (data.length != 0) {
rootOwner = abi.decode(data, (bytes32));
}
if (callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
return rootOwner;
uint256 rootOwnerInt = convertAddressToUint(rootOwnerAddress);
return (ERC998_MAGIC_VALUE << 224) | bytes32(rootOwnerInt);
}
}
| 12,980,435 |
pragma solidity ^0.4.24;
/*
* @title: VTRegistry Operator
* Registry Operators management
* Created on 2018-04-26, by Blockchain Labs, NZ
*/
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
contract Attribute is Ownable {
/*
* @dev: attributes used by registry (in records).
* @dev: Array of attributes is needed to iterate through them, and mapping is used to
* @dev: decrease the gas of checking whether the new attribute is need to be added to array or not.
*/
bytes32[] public attributes;
/*
* @dev: 'Attribute' mapping is used to keep information about available attributes
*/
mapping(bytes32 => bool) private attribute;
/*
* @dev: check if attribute exists
*/
function attributeExists(bytes32 _attribute) public view returns(bool) {
return(attribute[_attribute]);
}
/*
* @dev: add new attribute to mapping and array
*/
function addAttribute(bytes32 _attribute) internal onlyOwner returns(bool) {
attributes.push(_attribute);
attribute[_attribute] = true;
}
} | : attributes used by registry (in records). : Array of attributes is needed to iterate through them, and mapping is used to : decrease the gas of checking whether the new attribute is need to be added to array or not./ : 'Attribute' mapping is used to keep information about available attributes/ : check if attribute exists/ | function attributeExists(bytes32 _attribute) public view returns(bool) {
return(attribute[_attribute]);
}
| 5,498,506 |
./full_match/1/0xD045120193Df76261F5E10d5b0729a6e9137a426/sources/lion.sol | once enabled, can never be turned off | function enableTrading(bool _status, uint256 _deadBlocks) external onlyOwner {
require(!tradingActive, "DEXLIONS: trading is already active");
require(_deadBlocks <= 5, "DEXLIONS: deadblocks amount exceeds 5");
tradingActive = _status;
swapEnabled = true;
if (tradingActive && tradingActiveBlock == 0) {
tradingActiveBlock = block.number;
deadBlocks = _deadBlocks;
}
}
| 8,395,151 |
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.6.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
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 use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been 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) {
// 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.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/IRelayRecipient.sol
pragma solidity ^0.5.0;
/*
* @dev Interface for a contract that will be called via the GSN from RelayHub.
*/
contract IRelayRecipient {
/**
* @dev Returns the address of the RelayHub instance this recipient interacts with.
*/
function getHubAddr() public view returns (address);
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
function preRelayedCall(bytes calldata context) external returns (bytes32);
function postRelayedCall(bytes calldata context, bool success, uint actualCharge, bytes32 preRetVal) external;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/bouncers/GSNBouncerBase.sol
pragma solidity ^0.5.0;
/*
* @dev Base contract used to implement GSNBouncers.
*
* > This contract does not perform all required tasks to implement a GSN
* recipient contract: end users should use `GSNRecipient` instead.
*/
contract GSNBouncerBase is IRelayRecipient {
uint256 constant private RELAYED_CALL_ACCEPTED = 0;
uint256 constant private RELAYED_CALL_REJECTED = 11;
// How much gas is forwarded to postRelayedCall
uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000;
// Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the
// internal hook.
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* This function should not be overriden directly, use `_preRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32) {
require(msg.sender == getHubAddr(), "GSNBouncerBase: caller is not RelayHub");
return _preRelayedCall(context);
}
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* This function should not be overriden directly, use `_postRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external {
require(msg.sender == getHubAddr(), "GSNBouncerBase: caller is not RelayHub");
_postRelayedCall(context, success, actualCharge, preRetVal);
}
/**
* @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract
* will be charged a fee by RelayHub
*/
function _approveRelayedCall() internal pure returns (uint256, bytes memory) {
return _approveRelayedCall("");
}
/**
* @dev See `GSNBouncerBase._approveRelayedCall`.
*
* This overload forwards `context` to _preRelayedCall and _postRelayedCall.
*/
function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_ACCEPTED, context);
}
/**
* @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged.
*/
function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_REJECTED + errorCode, "");
}
// Empty hooks for pre and post relayed call: users only have to define these if they actually use them.
function _preRelayedCall(bytes memory) internal returns (bytes32) {
// solhint-disable-previous-line no-empty-blocks
}
function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal {
// solhint-disable-previous-line no-empty-blocks
}
/*
* @dev Calculates how much RelaHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's
* `serviceFee`.
*/
function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) {
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
// charged for 1.4 times the spent amount.
return (gas * gasPrice * (100 + serviceFee)) / 100;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol
pragma solidity ^0.5.2;
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECDSA {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// 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)))
}
// 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.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
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));
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/bouncers/GSNBouncerSignature.sol
pragma solidity ^0.5.0;
contract GSNBouncerSignature is Initializable, GSNBouncerBase {
using ECDSA for bytes32;
// We use a random storage slot to allow proxy contracts to enable GSN support in an upgrade without changing their
// storage layout. This value is calculated as: keccak256('gsn.bouncer.signature.trustedSigner'), minus 1.
bytes32 constant private TRUSTED_SIGNER_STORAGE_SLOT = 0xe7b237a4017a399d277819456dce32c2356236bbc518a6d84a9a8d1cfdf1e9c5;
enum GSNBouncerSignatureErrorCodes {
INVALID_SIGNER
}
function initialize(address trustedSigner) public initializer {
_setTrustedSigner(trustedSigner);
}
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256
)
external
view
returns (uint256, bytes memory)
{
bytes memory blob = abi.encodePacked(
relay,
from,
encodedFunction,
transactionFee,
gasPrice,
gasLimit,
nonce, // Prevents replays on RelayHub
getHubAddr(), // Prevents replays in multiple RelayHubs
address(this) // Prevents replays in multiple recipients
);
if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) == _getTrustedSigner()) {
return _approveRelayedCall();
} else {
return _rejectRelayedCall(uint256(GSNBouncerSignatureErrorCodes.INVALID_SIGNER));
}
}
function _getTrustedSigner() private view returns (address trustedSigner) {
bytes32 slot = TRUSTED_SIGNER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
trustedSigner := sload(slot)
}
}
function _setTrustedSigner(address trustedSigner) private {
bytes32 slot = TRUSTED_SIGNER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, trustedSigner)
}
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.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 not 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, with should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/GSNContext.sol
pragma solidity ^0.5.0;
/*
* @dev Enables GSN support on `Context` contracts by recognizing calls from
* RelayHub and extracting the actual sender and call data from the received
* calldata.
*
* > This contract does not perform all required tasks to implement a GSN
* recipient contract: end users should use `GSNRecipient` instead.
*/
contract GSNContext is Initializable, Context {
// We use a random storage slot to allow proxy contracts to enable GSN support in an upgrade without changing their
// storage layout. This value is calculated as: keccak256('gsn.relayhub.address'), minus 1.
bytes32 private constant RELAY_HUB_ADDRESS_STORAGE_SLOT = 0x06b7792c761dcc05af1761f0315ce8b01ac39c16cc934eb0b2f7a8e71414f262;
event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub);
function initialize() public initializer {
_upgradeRelayHub(0xD216153c06E857cD7f72665E0aF1d7D82172F494);
}
function _getRelayHub() internal view returns (address relayHub) {
bytes32 slot = RELAY_HUB_ADDRESS_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
relayHub := sload(slot)
}
}
function _upgradeRelayHub(address newRelayHub) internal {
address currentRelayHub = _getRelayHub();
require(newRelayHub != address(0), "GSNContext: new RelayHub is the zero address");
require(newRelayHub != currentRelayHub, "GSNContext: new RelayHub is the current one");
emit RelayHubChanged(currentRelayHub, newRelayHub);
bytes32 slot = RELAY_HUB_ADDRESS_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newRelayHub)
}
}
// Overrides for Context's functions: when called from RelayHub, sender and
// data require some pre-processing: the actual sender is stored at the end
// of the call data, which in turns means it needs to be removed from it
// when handling said data.
function _msgSender() internal view returns (address) {
if (msg.sender != _getRelayHub()) {
return msg.sender;
} else {
return _getRelayedCallSender();
}
}
function _msgData() internal view returns (bytes memory) {
if (msg.sender != _getRelayHub()) {
return msg.data;
} else {
return _getRelayedCallData();
}
}
function _getRelayedCallSender() private pure returns (address result) {
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
// bytes. This can always be done due to the 32-byte prefix.
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
// easiest/most-efficient way to perform this operation.
// These fields are not accessible from assembly
bytes memory array = msg.data;
uint256 index = msg.data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function _getRelayedCallData() private pure returns (bytes memory) {
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data,
// we must strip the last 20 bytes (length of an address type) from it.
uint256 actualDataLength = msg.data.length - 20;
bytes memory actualData = new bytes(actualDataLength);
for (uint256 i = 0; i < actualDataLength; ++i) {
actualData[i] = msg.data[i];
}
return actualData;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/IRelayHub.sol
pragma solidity ^0.5.0;
contract IRelayHub {
// Relay management
// Add stake to a relay and sets its unstakeDelay.
// If the relay does not exist, it is created, and the caller
// of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
// cannot be its own owner.
// All Ether in this function call will be added to the relay's stake.
// Its unstake delay will be assigned to unstakeDelay, but the new value must be greater or equal to the current one.
// Emits a Staked event.
function stake(address relayaddr, uint256 unstakeDelay) external payable;
// Emited when a relay's stake or unstakeDelay are increased
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
// Registers the caller as a relay.
// The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
// Emits a RelayAdded event.
// This function can be called multiple times, emitting new RelayAdded events. Note that the received transactionFee
// is not enforced by relayCall.
function registerRelay(uint256 transactionFee, string memory url) public;
// Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out RelayRemoved
// events) lets a client discover the list of available relays.
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
// Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. Can only be called by
// the owner of the relay. After the relay's unstakeDelay has elapsed, unstake will be callable.
// Emits a RelayRemoved event.
function removeRelayByOwner(address relay) public;
// Emitted when a relay is removed (deregistered). unstakeTime is the time when unstake will be callable.
event RelayRemoved(address indexed relay, uint256 unstakeTime);
// Deletes the relay from the system, and gives back its stake to the owner. Can only be called by the relay owner,
// after unstakeDelay has elapsed since removeRelayByOwner was called.
// Emits an Unstaked event.
function unstake(address relay) public;
// Emitted when a relay is unstaked for, including the returned stake.
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
// Returns a relay's status. Note that relays can be deleted when unstaked or penalized.
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
// Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only
// be withdrawn by the contract itself, by callingn withdraw.
// Emits a Deposited event.
function depositFor(address target) public payable;
// Emitted when depositFor is called, including the amount and account that was funded.
event Deposited(address indexed recipient, address indexed from, uint256 amount);
// Returns an account's deposits. These can be either a contnract's funds, or a relay owner's revenue.
function balanceOf(address target) external view returns (uint256);
// Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
// contracts can also use it to reduce their funding.
// Emits a Withdrawn event.
function withdraw(uint256 amount, address payable dest) public;
// Emitted when an account withdraws funds from RelayHub.
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
// Check if the RelayHub will accept a relayed operation. Multiple things must be true for this to happen:
// - all arguments must be signed for by the sender (from)
// - the sender's nonce must be the current one
// - the recipient must accept this transaction (via acceptRelayedCall)
// Returns a PreconditionCheck value (OK when the transaction can be relayed), or a recipient-specific error code if
// it returns one in acceptRelayedCall.
function canRelay(
address relay,
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
// Relays a transaction. For this to suceed, multiple conditions must be met:
// - canRelay must return PreconditionCheck.OK
// - the sender must be a registered relay
// - the transaction's gas price must be larger or equal to the one that was requested by the sender
// - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
// recipient) use all gas available to them
// - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
// spent)
//
// If all conditions are met, the call will be relayed and the recipient charged. preRelayedCall, the encoded
// function and postRelayedCall will be called in order.
//
// Arguments:
// - from: the client originating the request
// - recipient: the target IRelayRecipient contract
// - encodedFunction: the function call to relay, including data
// - transactionFee: fee (%) the relay takes over actual gas cost
// - gasPrice: gas price the client is willing to pay
// - gasLimit: gas to forward when calling the encoded function
// - nonce: client's nonce
// - signature: client's signature over all previous params, plus the relay and RelayHub addresses
// - approvalData: dapp-specific data forwared to acceptRelayedCall. This value is *not* verified by the Hub, but
// it still can be used for e.g. a signature.
//
// Emits a TransactionRelayed event.
function relayCall(
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public;
// Emitted when an attempt to relay a call failed. This can happen due to incorrect relayCall arguments, or the
// recipient not accepting the relayed call. The actual relayed call was not executed, and the recipient not charged.
// The reason field contains an error code: values 1-10 correspond to PreconditionCheck entries, and values over 10
// are custom recipient error codes returned from acceptRelayedCall.
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
// Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be
// indicated in the status field.
// Useful when monitoring a relay's operation and relayed calls to a contract.
// Charge is the ether value deducted from the recipient's balance, paid to the relay's owner.
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
// Returns how much gas should be forwarded to a call to relayCall, in order to relay a transaction that will spend
// up to relayedCallStipend gas.
function requiredGas(uint256 relayedCallStipend) public view returns (uint256);
// Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256);
// Relay penalization. Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
// Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
// different data (gas price, gas limit, etc. may be different). The (unsigned) transaction data and signature for
// both transactions must be provided.
function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public;
// Penalize a relay that sent a transaction that didn't target RelayHub's registerRelay or relayCall.
function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public;
event Penalized(address indexed relay, address sender, uint256 amount);
function getNonce(address from) external view returns (uint256);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/GSNRecipient.sol
pragma solidity ^0.5.0;
/*
* @dev Base GSN recipient contract, adding the recipient interface and enabling
* GSN support. Not all interface methods are implemented, derived contracts
* must do so themselves.
*/
contract GSNRecipient is Initializable, IRelayRecipient, GSNContext, GSNBouncerBase {
function initialize() public initializer {
GSNContext.initialize();
}
function getHubAddr() public view returns (address) {
return _getRelayHub();
}
// This function is view for future-proofing, it may require reading from
// storage in the future.
function relayHubVersion() public view returns (string memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return "1.0.0";
}
function _withdrawDeposits(uint256 amount, address payable payee) internal {
IRelayHub(_getRelayHub()).withdraw(amount, payee);
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
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);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.2;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard is Initializable {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
uint256[50] private ______gap;
}
// File: @sablier/shared-contracts/compound/CarefulMath.sol
pragma solidity ^0.5.8;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// File: @sablier/shared-contracts/compound/Exponential.sol
pragma solidity ^0.5.8;
/**
* @title Exponential module for storing fixed-decision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo.
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
}
// File: @sablier/shared-contracts/interfaces/ICERC20.sol
pragma solidity 0.5.11;
/**
* @title CERC20 interface
* @author Sablier
* @dev See https://compound.finance/developers
*/
interface ICERC20 {
function balanceOf(address who) external view returns (uint256);
function isCToken() external view returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function balanceOfUnderlying(address account) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// File: @sablier/shared-contracts/lifecycle/OwnableWithoutRenounce.sol
pragma solidity 0.5.11;
/**
* @title OwnableWithoutRenounce
* @author Sablier
* @dev Fork of OpenZeppelin's Ownable contract, which provides basic authorization control, but with
* the `renounceOwnership` function removed to avoid fat-finger errors.
* We inherit from `Context` to keep this contract compatible with the Gas Station Network.
* See https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/ownership/Ownable.sol
* See https://forum.openzeppelin.com/t/contract-request-ownable-without-renounceownership/1400
* See https://docs.openzeppelin.com/contracts/2.x/gsn#_msg_sender_and_msg_data
*/
contract OwnableWithoutRenounce is Initializable, Context {
address private _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 initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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 _msgSender() == _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 {
_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;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol
pragma solidity ^0.5.2;
/**
* @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));
require(!has(role, account));
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));
require(has(role, account));
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];
}
}
// File: @sablier/shared-contracts/lifecycle/PauserRoleWithoutRenounce.sol
pragma solidity ^0.5.0;
/**
* @title PauserRoleWithoutRenounce
* @author Sablier
* @notice Fork of OpenZeppelin's PauserRole, but with the `renouncePauser` function removed to avoid fat-finger errors.
* We inherit from `Context` to keep this contract compatible with the Gas Station Network.
* See https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/access/roles/PauserRole.sol
*/
contract PauserRoleWithoutRenounce is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
// File: @sablier/shared-contracts/lifecycle/PausableWithoutRenounce.sol
pragma solidity 0.5.11;
/**
* @title PausableWithoutRenounce
* @author Sablier
* @notice Fork of OpenZeppelin's Pausable, a contract module which allows children to implement an
* emergency stop mechanism that can be triggered by an authorized account, but with the `renouncePauser`
* function removed to avoid fat-finger errors.
* We inherit from `Context` to keep this contract compatible with the Gas Station Network.
* See https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/lifecycle/Pausable.sol
* See https://docs.openzeppelin.com/contracts/2.x/gsn#_msg_sender_and_msg_data
*/
contract PausableWithoutRenounce is Initializable, Context, PauserRoleWithoutRenounce {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
function initialize(address sender) public initializer {
PauserRoleWithoutRenounce.initialize(sender);
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @sablier/protocol/contracts/interfaces/ICTokenManager.sol
pragma solidity 0.5.11;
/**
* @title CTokenManager Interface
* @author Sablier
*/
interface ICTokenManager {
/**
* @notice Emits when the owner discards a cToken.
*/
event DiscardCToken(address indexed tokenAddress);
/**
* @notice Emits when the owner whitelists a cToken.
*/
event WhitelistCToken(address indexed tokenAddress);
function whitelistCToken(address tokenAddress) external;
function discardCToken(address tokenAddress) external;
function isCToken(address tokenAddress) external view returns (bool);
}
// File: @sablier/protocol/contracts/interfaces/IERC1620.sol
pragma solidity 0.5.11;
/**
* @title ERC-1620 Money Streaming Standard
* @author Paul Razvan Berg - <[email protected]>
* @dev See https://eips.ethereum.org/EIPS/eip-1620
*/
interface IERC1620 {
/**
* @notice Emits when a stream is successfully created.
*/
event CreateStream(
uint256 indexed streamId,
address indexed sender,
address indexed recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime
);
/**
* @notice Emits when the recipient of a stream withdraws a portion or all their pro rata share of the stream.
*/
event WithdrawFromStream(uint256 indexed streamId, address indexed recipient, uint256 amount);
/**
* @notice Emits when a stream is successfully cancelled and tokens are transferred back on a pro rata basis.
*/
event CancelStream(
uint256 indexed streamId,
address indexed sender,
address indexed recipient,
uint256 senderBalance,
uint256 recipientBalance
);
function balanceOf(uint256 streamId, address who) external view returns (uint256 balance);
function getStream(uint256 streamId)
external
view
returns (
address sender,
address recipient,
uint256 deposit,
address token,
uint256 startTime,
uint256 stopTime,
uint256 balance,
uint256 rate
);
function createStream(address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime)
external
returns (uint256 streamId);
function withdrawFromStream(uint256 streamId, uint256 funds) external returns (bool);
function cancelStream(uint256 streamId) external returns (bool);
}
// File: @sablier/protocol/contracts/Types.sol
pragma solidity 0.5.11;
/**
* @title Sablier Types
* @author Sablier
*/
library Types {
struct Stream {
uint256 deposit;
uint256 ratePerSecond;
uint256 remainingBalance;
uint256 startTime;
uint256 stopTime;
address recipient;
address sender;
address tokenAddress;
bool isEntity;
}
struct CompoundingStreamVars {
Exponential.Exp exchangeRateInitial;
Exponential.Exp senderShare;
Exponential.Exp recipientShare;
bool isEntity;
}
}
// File: @sablier/protocol/contracts/Sablier.sol
pragma solidity 0.5.11;
/**
* @title Sablier's Money Streaming
* @author Sablier
*/
contract Sablier is IERC1620, OwnableWithoutRenounce, PausableWithoutRenounce, Exponential, ReentrancyGuard {
/*** Storage Properties ***/
/**
* @notice In Exp terms, 1e18 is 1, or 100%
*/
uint256 constant hundredPercent = 1e18;
/**
* @notice In Exp terms, 1e16 is 0.01, or 1%
*/
uint256 constant onePercent = 1e16;
/**
* @notice Stores information about the initial state of the underlying of the cToken.
*/
mapping(uint256 => Types.CompoundingStreamVars) private compoundingStreamsVars;
/**
* @notice An instance of CTokenManager, responsible for whitelisting and discarding cTokens.
*/
ICTokenManager public cTokenManager;
/**
* @notice The amount of interest has been accrued per token address.
*/
mapping(address => uint256) private earnings;
/**
* @notice The percentage fee charged by the contract on the accrued interest.
*/
Exp public fee;
/**
* @notice Counter for new stream ids.
*/
uint256 public nextStreamId;
/**
* @notice The stream objects identifiable by their unsigned integer ids.
*/
mapping(uint256 => Types.Stream) private streams;
/*** Events ***/
/**
* @notice Emits when a compounding stream is successfully created.
*/
event CreateCompoundingStream(
uint256 indexed streamId,
uint256 exchangeRate,
uint256 senderSharePercentage,
uint256 recipientSharePercentage
);
/**
* @notice Emits when the owner discards a cToken.
*/
event PayInterest(uint256 streamId, uint256 senderInterest, uint256 recipientInterest, uint256 sablierInterest);
/**
* @notice Emits when the owner takes the earnings.
*/
event TakeEarnings(address indexed tokenAddress, uint256 indexed amount);
/**
* @notice Emits when the owner updates the percentage fee.
*/
event UpdateFee(uint256 indexed fee);
/*** Modifiers ***/
/**
* @dev Throws if the caller is not the sender of the recipient of the stream.
*/
modifier onlySenderOrRecipient(uint256 streamId) {
require(
msg.sender == streams[streamId].sender || msg.sender == streams[streamId].recipient,
"caller is not the sender or the recipient of the stream"
);
_;
}
/**
* @dev Throws if the id does not point to a valid stream.
*/
modifier streamExists(uint256 streamId) {
require(streams[streamId].isEntity, "stream does not exist");
_;
}
/**
* @dev Throws if the id does not point to a valid compounding stream.
*/
modifier compoundingStreamExists(uint256 streamId) {
require(compoundingStreamsVars[streamId].isEntity, "compounding stream does not exist");
_;
}
/*** Contract Logic Starts Here */
constructor(address cTokenManagerAddress) public {
OwnableWithoutRenounce.initialize(msg.sender);
PausableWithoutRenounce.initialize(msg.sender);
cTokenManager = ICTokenManager(cTokenManagerAddress);
nextStreamId = 1;
}
/*** Owner Functions ***/
struct UpdateFeeLocalVars {
MathError mathErr;
uint256 feeMantissa;
}
/**
* @notice Updates the Sablier fee.
* @dev Throws if the caller is not the owner of the contract.
* Throws if `feePercentage` is not lower or equal to 100.
* @param feePercentage The new fee as a percentage.
*/
function updateFee(uint256 feePercentage) external onlyOwner {
require(feePercentage <= 100, "fee percentage higher than 100%");
UpdateFeeLocalVars memory vars;
/* `feePercentage` will be stored as a mantissa, so we scale it up by one percent in Exp terms. */
(vars.mathErr, vars.feeMantissa) = mulUInt(feePercentage, onePercent);
/*
* `mulUInt` can only return MathError.INTEGER_OVERFLOW but we control `onePercent`
* and we know `feePercentage` is maximum 100.
*/
assert(vars.mathErr == MathError.NO_ERROR);
fee = Exp({ mantissa: vars.feeMantissa });
emit UpdateFee(feePercentage);
}
struct TakeEarningsLocalVars {
MathError mathErr;
}
/**
* @notice Withdraws the earnings for the given token address.
* @dev Throws if `amount` exceeds the available blance.
* @param tokenAddress The address of the token to withdraw earnings for.
* @param amount The amount of tokens to withdraw.
*/
function takeEarnings(address tokenAddress, uint256 amount) external onlyOwner nonReentrant {
require(cTokenManager.isCToken(tokenAddress), "cToken is not whitelisted");
require(amount > 0, "amount is zero");
require(earnings[tokenAddress] >= amount, "amount exceeds the available balance");
TakeEarningsLocalVars memory vars;
(vars.mathErr, earnings[tokenAddress]) = subUInt(earnings[tokenAddress], amount);
/*
* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know `earnings[tokenAddress]`
* is at least as big as `amount`.
*/
assert(vars.mathErr == MathError.NO_ERROR);
emit TakeEarnings(tokenAddress, amount);
require(IERC20(tokenAddress).transfer(msg.sender, amount), "token transfer failure");
}
/*** View Functions ***/
/**
* @notice Returns the compounding stream with all its properties.
* @dev Throws if the id does not point to a valid stream.
* @param streamId The id of the stream to query.
* @return The stream object.
*/
function getStream(uint256 streamId)
external
view
streamExists(streamId)
returns (
address sender,
address recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime,
uint256 remainingBalance,
uint256 ratePerSecond
)
{
sender = streams[streamId].sender;
recipient = streams[streamId].recipient;
deposit = streams[streamId].deposit;
tokenAddress = streams[streamId].tokenAddress;
startTime = streams[streamId].startTime;
stopTime = streams[streamId].stopTime;
remainingBalance = streams[streamId].remainingBalance;
ratePerSecond = streams[streamId].ratePerSecond;
}
/**
* @notice Returns either the delta in seconds between `block.timestmap and `startTime` or
* between `stopTime` and `startTime, whichever is smaller. If `block.timestamp` is before
* `startTime`, it returns 0.
* @dev Throws if the id does not point to a valid stream.
* @param streamId The id of the stream for whom to query the delta.
* @return The time delta in seconds.
*/
function deltaOf(uint256 streamId) public view streamExists(streamId) returns (uint256 delta) {
Types.Stream memory stream = streams[streamId];
if (block.timestamp <= stream.startTime) return 0;
if (block.timestamp < stream.stopTime) return block.timestamp - stream.startTime;
return stream.stopTime - stream.startTime;
}
struct BalanceOfLocalVars {
MathError mathErr;
uint256 recipientBalance;
uint256 withdrawalAmount;
uint256 senderBalance;
}
/**
* @notice Returns the available funds for the given stream id and address.
* @dev Throws if the id does not point to a valid stream.
* @param streamId The id of the stream for whom to query the balance.
* @param who The address for whom to query the balance.
* @return The total funds allocated to `who` as uint256.
*/
function balanceOf(uint256 streamId, address who) public view streamExists(streamId) returns (uint256 balance) {
Types.Stream memory stream = streams[streamId];
BalanceOfLocalVars memory vars;
uint256 delta = deltaOf(streamId);
(vars.mathErr, vars.recipientBalance) = mulUInt(delta, stream.ratePerSecond);
require(vars.mathErr == MathError.NO_ERROR, "recipient balance calculation error");
/*
* If the stream `balance` does not equal `deposit`, it means there have been withdrawals.
* We have to subtract the total amount withdrawn from the amount of money that has been
* streamed until now.
*/
if (stream.deposit > stream.remainingBalance) {
(vars.mathErr, vars.withdrawalAmount) = subUInt(stream.deposit, stream.remainingBalance);
assert(vars.mathErr == MathError.NO_ERROR);
(vars.mathErr, vars.recipientBalance) = subUInt(vars.recipientBalance, vars.withdrawalAmount);
/* `withdrawalAmount` cannot and should not be bigger than `recipientBalance`. */
assert(vars.mathErr == MathError.NO_ERROR);
}
if (who == stream.recipient) return vars.recipientBalance;
if (who == stream.sender) {
(vars.mathErr, vars.senderBalance) = subUInt(stream.remainingBalance, vars.recipientBalance);
/* `recipientBalance` cannot and should not be bigger than `remainingBalance`. */
assert(vars.mathErr == MathError.NO_ERROR);
return vars.senderBalance;
}
return 0;
}
/**
* @notice Checks if the given id points to a compounding stream.
* @param streamId The id of the compounding stream to check.
* @return bool true=it is compounding stream, otherwise false.
*/
function isCompoundingStream(uint256 streamId) public view returns (bool) {
return compoundingStreamsVars[streamId].isEntity;
}
/**
* @notice Returns the compounding stream object with all its properties.
* @dev Throws if the id does not point to a valid compounding stream.
* @param streamId The id of the compounding stream to query.
* @return The compounding stream object.
*/
function getCompoundingStream(uint256 streamId)
external
view
streamExists(streamId)
compoundingStreamExists(streamId)
returns (
address sender,
address recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime,
uint256 remainingBalance,
uint256 ratePerSecond,
uint256 exchangeRateInitial,
uint256 senderSharePercentage,
uint256 recipientSharePercentage
)
{
sender = streams[streamId].sender;
recipient = streams[streamId].recipient;
deposit = streams[streamId].deposit;
tokenAddress = streams[streamId].tokenAddress;
startTime = streams[streamId].startTime;
stopTime = streams[streamId].stopTime;
remainingBalance = streams[streamId].remainingBalance;
ratePerSecond = streams[streamId].ratePerSecond;
exchangeRateInitial = compoundingStreamsVars[streamId].exchangeRateInitial.mantissa;
senderSharePercentage = compoundingStreamsVars[streamId].senderShare.mantissa;
recipientSharePercentage = compoundingStreamsVars[streamId].recipientShare.mantissa;
}
struct InterestOfLocalVars {
MathError mathErr;
Exp exchangeRateDelta;
Exp underlyingInterest;
Exp netUnderlyingInterest;
Exp senderUnderlyingInterest;
Exp recipientUnderlyingInterest;
Exp sablierUnderlyingInterest;
Exp senderInterest;
Exp recipientInterest;
Exp sablierInterest;
}
/**
* @notice Computes the interest accrued by keeping the amount of tokens in the contract. Returns (0, 0, 0) if
* the stream is not a compounding stream.
* @dev Throws if there is a math error. We do not assert the calculations which involve the current
* exchange rate, because we can't know what value we'll get back from the cToken contract.
* @return The interest accrued by the sender, the recipient and sablier, respectively, as uint256s.
*/
function interestOf(uint256 streamId, uint256 amount)
public
streamExists(streamId)
returns (uint256 senderInterest, uint256 recipientInterest, uint256 sablierInterest)
{
if (!compoundingStreamsVars[streamId].isEntity) {
return (0, 0, 0);
}
Types.Stream memory stream = streams[streamId];
Types.CompoundingStreamVars memory compoundingStreamVars = compoundingStreamsVars[streamId];
InterestOfLocalVars memory vars;
/*
* The exchange rate delta is a key variable, since it leads us to how much interest has been earned
* since the compounding stream was created.
*/
Exp memory exchangeRateCurrent = Exp({ mantissa: ICERC20(stream.tokenAddress).exchangeRateCurrent() });
if (exchangeRateCurrent.mantissa <= compoundingStreamVars.exchangeRateInitial.mantissa) {
return (0, 0, 0);
}
(vars.mathErr, vars.exchangeRateDelta) = subExp(exchangeRateCurrent, compoundingStreamVars.exchangeRateInitial);
assert(vars.mathErr == MathError.NO_ERROR);
/* Calculate how much interest has been earned by holding `amount` in the smart contract. */
(vars.mathErr, vars.underlyingInterest) = mulScalar(vars.exchangeRateDelta, amount);
require(vars.mathErr == MathError.NO_ERROR, "interest calculation error");
/* Calculate our share from that interest. */
if (fee.mantissa == hundredPercent) {
(vars.mathErr, vars.sablierInterest) = divExp(vars.underlyingInterest, exchangeRateCurrent);
require(vars.mathErr == MathError.NO_ERROR, "sablier interest conversion error");
return (0, 0, truncate(vars.sablierInterest));
} else if (fee.mantissa == 0) {
vars.sablierUnderlyingInterest = Exp({ mantissa: 0 });
vars.netUnderlyingInterest = vars.underlyingInterest;
} else {
(vars.mathErr, vars.sablierUnderlyingInterest) = mulExp(vars.underlyingInterest, fee);
require(vars.mathErr == MathError.NO_ERROR, "sablier interest calculation error");
/* Calculate how much interest is left for the sender and the recipient. */
(vars.mathErr, vars.netUnderlyingInterest) = subExp(
vars.underlyingInterest,
vars.sablierUnderlyingInterest
);
/*
* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `sablierUnderlyingInterest`
* is less or equal than `underlyingInterest`, because we control the value of `fee`.
*/
assert(vars.mathErr == MathError.NO_ERROR);
}
/* Calculate the sender's share of the interest. */
(vars.mathErr, vars.senderUnderlyingInterest) = mulExp(
vars.netUnderlyingInterest,
compoundingStreamVars.senderShare
);
require(vars.mathErr == MathError.NO_ERROR, "sender interest calculation error");
/* Calculate the recipient's share of the interest. */
(vars.mathErr, vars.recipientUnderlyingInterest) = subExp(
vars.netUnderlyingInterest,
vars.senderUnderlyingInterest
);
/*
* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `senderUnderlyingInterest`
* is less or equal than `netUnderlyingInterest`, because `senderShare` is bounded between 1e16 and 1e18.
*/
assert(vars.mathErr == MathError.NO_ERROR);
/* Convert the interest to the equivalent cToken denomination. */
(vars.mathErr, vars.senderInterest) = divExp(vars.senderUnderlyingInterest, exchangeRateCurrent);
require(vars.mathErr == MathError.NO_ERROR, "sender interest conversion error");
(vars.mathErr, vars.recipientInterest) = divExp(vars.recipientUnderlyingInterest, exchangeRateCurrent);
require(vars.mathErr == MathError.NO_ERROR, "recipient interest conversion error");
(vars.mathErr, vars.sablierInterest) = divExp(vars.sablierUnderlyingInterest, exchangeRateCurrent);
require(vars.mathErr == MathError.NO_ERROR, "sablier interest conversion error");
/* Truncating the results means losing everything on the last 1e18 positions of the mantissa */
return (truncate(vars.senderInterest), truncate(vars.recipientInterest), truncate(vars.sablierInterest));
}
/**
* @notice Returns the amount of interest that has been accrued for the given token address.
* @param tokenAddress The address of the token to get the earnings for.
* @return The amount of interest as uint256.
*/
function getEarnings(address tokenAddress) external view returns (uint256) {
require(cTokenManager.isCToken(tokenAddress), "token is not cToken");
return earnings[tokenAddress];
}
/*** Public Effects & Interactions Functions ***/
struct CreateStreamLocalVars {
MathError mathErr;
uint256 duration;
uint256 ratePerSecond;
}
/**
* @notice Creates a new stream funded by `msg.sender` and paid towards `recipient`.
* @dev Throws if paused.
* Throws if the recipient is the zero address, the contract itself or the caller.
* Throws if the deposit is 0.
* Throws if the start time is before `block.timestamp`.
* Throws if the stop time is before the start time.
* Throws if the duration calculation has a math error.
* Throws if the deposit is smaller than the duration.
* Throws if the deposit is not a multiple of the duration.
* Throws if the rate calculation has a math error.
* Throws if the next stream id calculation has a math error.
* Throws if the contract is not allowed to transfer enough tokens.
* Throws if there is a token transfer failure.
* @param recipient The address towards which the money is streamed.
* @param deposit The amount of money to be streamed.
* @param tokenAddress The ERC20 token to use as streaming currency.
* @param startTime The unix timestamp for when the stream starts.
* @param stopTime The unix timestamp for when the stream stops.
* @return The uint256 id of the newly created stream.
*/
function createStream(address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime)
public
whenNotPaused
returns (uint256)
{
require(recipient != address(0x00), "stream to the zero address");
require(recipient != address(this), "stream to the contract itself");
require(recipient != msg.sender, "stream to the caller");
require(deposit > 0, "deposit is zero");
require(startTime >= block.timestamp, "start time before block.timestamp");
require(stopTime > startTime, "stop time before the start time");
CreateStreamLocalVars memory vars;
(vars.mathErr, vars.duration) = subUInt(stopTime, startTime);
/* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know `stopTime` is higher than `startTime`. */
assert(vars.mathErr == MathError.NO_ERROR);
/* Without this, the rate per second would be zero. */
require(deposit >= vars.duration, "deposit smaller than time delta");
/* This condition avoids dealing with remainders */
require(deposit % vars.duration == 0, "deposit not multiple of time delta");
(vars.mathErr, vars.ratePerSecond) = divUInt(deposit, vars.duration);
/* `divUInt` can only return MathError.DIVISION_BY_ZERO but we know `duration` is not zero. */
assert(vars.mathErr == MathError.NO_ERROR);
/* Create and store the stream object. */
uint256 streamId = nextStreamId;
streams[streamId] = Types.Stream({
remainingBalance: deposit,
deposit: deposit,
isEntity: true,
ratePerSecond: vars.ratePerSecond,
recipient: recipient,
sender: msg.sender,
startTime: startTime,
stopTime: stopTime,
tokenAddress: tokenAddress
});
/* Increment the next stream id. */
(vars.mathErr, nextStreamId) = addUInt(nextStreamId, uint256(1));
require(vars.mathErr == MathError.NO_ERROR, "next stream id calculation error");
require(IERC20(tokenAddress).transferFrom(msg.sender, address(this), deposit), "token transfer failure");
emit CreateStream(streamId, msg.sender, recipient, deposit, tokenAddress, startTime, stopTime);
return streamId;
}
struct CreateCompoundingStreamLocalVars {
MathError mathErr;
uint256 shareSum;
uint256 underlyingBalance;
uint256 senderShareMantissa;
uint256 recipientShareMantissa;
}
/**
* @notice Creates a new compounding stream funded by `msg.sender` and paid towards `recipient`.
* @dev Inherits all security checks from `createStream`.
* Throws if the cToken is not whitelisted.
* Throws if the sender share percentage and the recipient share percentage do not sum up to 100.
* Throws if the the sender share mantissa calculation has a math error.
* Throws if the the recipient share mantissa calculation has a math error.
* @param recipient The address towards which the money is streamed.
* @param deposit The amount of money to be streamed.
* @param tokenAddress The ERC20 token to use as streaming currency.
* @param startTime The unix timestamp for when the stream starts.
* @param stopTime The unix timestamp for when the stream stops.
* @param senderSharePercentage The sender's share of the interest, as a percentage.
* @param recipientSharePercentage The sender's share of the interest, as a percentage.
* @return The uint256 id of the newly created compounding stream.
*/
function createCompoundingStream(
address recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime,
uint256 senderSharePercentage,
uint256 recipientSharePercentage
) external whenNotPaused returns (uint256) {
require(cTokenManager.isCToken(tokenAddress), "cToken is not whitelisted");
CreateCompoundingStreamLocalVars memory vars;
/* Ensure that the interest shares sum up to 100%. */
(vars.mathErr, vars.shareSum) = addUInt(senderSharePercentage, recipientSharePercentage);
require(vars.mathErr == MathError.NO_ERROR, "share sum calculation error");
require(vars.shareSum == 100, "shares do not sum up to 100");
uint256 streamId = createStream(recipient, deposit, tokenAddress, startTime, stopTime);
/*
* `senderSharePercentage` and `recipientSharePercentage` will be stored as mantissas, so we scale them up
* by one percent in Exp terms.
*/
(vars.mathErr, vars.senderShareMantissa) = mulUInt(senderSharePercentage, onePercent);
/*
* `mulUInt` can only return MathError.INTEGER_OVERFLOW but we control `onePercent` and
* we know `senderSharePercentage` is maximum 100.
*/
assert(vars.mathErr == MathError.NO_ERROR);
(vars.mathErr, vars.recipientShareMantissa) = mulUInt(recipientSharePercentage, onePercent);
/*
* `mulUInt` can only return MathError.INTEGER_OVERFLOW but we control `onePercent` and
* we know `recipientSharePercentage` is maximum 100.
*/
assert(vars.mathErr == MathError.NO_ERROR);
/* Create and store the compounding stream vars. */
uint256 exchangeRateCurrent = ICERC20(tokenAddress).exchangeRateCurrent();
compoundingStreamsVars[streamId] = Types.CompoundingStreamVars({
exchangeRateInitial: Exp({ mantissa: exchangeRateCurrent }),
isEntity: true,
recipientShare: Exp({ mantissa: vars.recipientShareMantissa }),
senderShare: Exp({ mantissa: vars.senderShareMantissa })
});
emit CreateCompoundingStream(streamId, exchangeRateCurrent, senderSharePercentage, recipientSharePercentage);
return streamId;
}
/**
* @notice Withdraws from the contract to the recipient's account.
* @dev Throws if the id does not point to a valid stream.
* Throws if the caller is not the sender or the recipient of the stream.
* Throws if the amount exceeds the available balance.
* Throws if there is a token transfer failure.
* @param streamId The id of the stream to withdraw tokens from.
* @param amount The amount of tokens to withdraw.
* @return bool true=success, otherwise false.
*/
function withdrawFromStream(uint256 streamId, uint256 amount)
external
whenNotPaused
nonReentrant
streamExists(streamId)
onlySenderOrRecipient(streamId)
returns (bool)
{
require(amount > 0, "amount is zero");
Types.Stream memory stream = streams[streamId];
uint256 balance = balanceOf(streamId, stream.recipient);
require(balance >= amount, "amount exceeds the available balance");
if (!compoundingStreamsVars[streamId].isEntity) {
withdrawFromStreamInternal(streamId, amount);
} else {
withdrawFromCompoundingStreamInternal(streamId, amount);
}
return true;
}
/**
* @notice Cancels the stream and transfers the tokens back on a pro rata basis.
* @dev Throws if the id does not point to a valid stream.
* Throws if the caller is not the sender or the recipient of the stream.
* Throws if there is a token transfer failure.
* @param streamId The id of the stream to cancel.
* @return bool true=success, otherwise false.
*/
function cancelStream(uint256 streamId)
external
nonReentrant
streamExists(streamId)
onlySenderOrRecipient(streamId)
returns (bool)
{
if (!compoundingStreamsVars[streamId].isEntity) {
cancelStreamInternal(streamId);
} else {
cancelCompoundingStreamInternal(streamId);
}
return true;
}
/*** Internal Effects & Interactions Functions ***/
struct WithdrawFromStreamInternalLocalVars {
MathError mathErr;
}
/**
* @notice Makes the withdrawal to the recipient of the stream.
* @dev If the stream balance has been depleted to 0, the stream object is deleted
* to save gas and optimise contract storage.
* Throws if the stream balance calculation has a math error.
* Throws if there is a token transfer failure.
*/
function withdrawFromStreamInternal(uint256 streamId, uint256 amount) internal {
Types.Stream memory stream = streams[streamId];
WithdrawFromStreamInternalLocalVars memory vars;
(vars.mathErr, streams[streamId].remainingBalance) = subUInt(stream.remainingBalance, amount);
/**
* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `remainingBalance` is at least
* as big as `amount`. See the `require` check in `withdrawFromInternal`.
*/
assert(vars.mathErr == MathError.NO_ERROR);
if (streams[streamId].remainingBalance == 0) delete streams[streamId];
require(IERC20(stream.tokenAddress).transfer(stream.recipient, amount), "token transfer failure");
emit WithdrawFromStream(streamId, stream.recipient, amount);
}
struct WithdrawFromCompoundingStreamInternalLocalVars {
MathError mathErr;
uint256 amountWithoutSenderInterest;
uint256 netWithdrawalAmount;
}
/**
* @notice Withdraws to the recipient's account and pays the accrued interest to all parties.
* @dev If the stream balance has been depleted to 0, the stream object to save gas and optimise
* contract storage.
* Throws if there is a math error.
* Throws if there is a token transfer failure.
*/
function withdrawFromCompoundingStreamInternal(uint256 streamId, uint256 amount) internal {
Types.Stream memory stream = streams[streamId];
WithdrawFromCompoundingStreamInternalLocalVars memory vars;
/* Calculate the interest earned by each party for keeping `stream.balance` in the smart contract. */
(uint256 senderInterest, uint256 recipientInterest, uint256 sablierInterest) = interestOf(streamId, amount);
/*
* Calculate the net withdrawal amount by subtracting `senderInterest` and `sablierInterest`.
* Because the decimal points are lost when we truncate Exponentials, the recipient will implicitly earn
* `recipientInterest` plus a tiny-weeny amount of interest, max 2e-8 in cToken denomination.
*/
(vars.mathErr, vars.amountWithoutSenderInterest) = subUInt(amount, senderInterest);
require(vars.mathErr == MathError.NO_ERROR, "amount without sender interest calculation error");
(vars.mathErr, vars.netWithdrawalAmount) = subUInt(vars.amountWithoutSenderInterest, sablierInterest);
require(vars.mathErr == MathError.NO_ERROR, "net withdrawal amount calculation error");
/* Subtract `amount` from the remaining balance of the stream. */
(vars.mathErr, streams[streamId].remainingBalance) = subUInt(stream.remainingBalance, amount);
require(vars.mathErr == MathError.NO_ERROR, "balance subtraction calculation error");
/* Delete the objects from storage if the remainig balance has been depleted to 0. */
if (streams[streamId].remainingBalance == 0) {
delete streams[streamId];
delete compoundingStreamsVars[streamId];
}
/* Add the sablier interest to the earnings for this cToken. */
(vars.mathErr, earnings[stream.tokenAddress]) = addUInt(earnings[stream.tokenAddress], sablierInterest);
require(vars.mathErr == MathError.NO_ERROR, "earnings addition calculation error");
/* Transfer the tokens to the sender and the recipient. */
ICERC20 cToken = ICERC20(stream.tokenAddress);
if (senderInterest > 0)
require(cToken.transfer(stream.sender, senderInterest), "sender token transfer failure");
require(cToken.transfer(stream.recipient, vars.netWithdrawalAmount), "recipient token transfer failure");
emit WithdrawFromStream(streamId, stream.recipient, vars.netWithdrawalAmount);
emit PayInterest(streamId, senderInterest, recipientInterest, sablierInterest);
}
/**
* @notice Cancels the stream and transfers the tokens back on a pro rata basis.
* @dev The stream and compounding stream vars objects get deleted to save gas
* and optimise contract storage.
* Throws if there is a token transfer failure.
*/
function cancelStreamInternal(uint256 streamId) internal {
Types.Stream memory stream = streams[streamId];
uint256 senderBalance = balanceOf(streamId, stream.sender);
uint256 recipientBalance = balanceOf(streamId, stream.recipient);
delete streams[streamId];
IERC20 token = IERC20(stream.tokenAddress);
if (recipientBalance > 0)
require(token.transfer(stream.recipient, recipientBalance), "recipient token transfer failure");
if (senderBalance > 0) require(token.transfer(stream.sender, senderBalance), "sender token transfer failure");
emit CancelStream(streamId, stream.sender, stream.recipient, senderBalance, recipientBalance);
}
struct CancelCompoundingStreamInternal {
MathError mathErr;
uint256 netSenderBalance;
uint256 recipientBalanceWithoutSenderInterest;
uint256 netRecipientBalance;
}
/**
* @notice Cancels the stream, transfers the tokens back on a pro rata basis and pays the accrued
* interest to all parties.
* @dev Importantly, the money that has not been streamed yet is not considered chargeable.
* All the interest generated by that underlying will be returned to the sender.
* Throws if there is a math error.
* Throws if there is a token transfer failure.
*/
function cancelCompoundingStreamInternal(uint256 streamId) internal {
Types.Stream memory stream = streams[streamId];
CancelCompoundingStreamInternal memory vars;
/*
* The sender gets back all the money that has not been streamed so far. By that, we mean both
* the underlying amount and the interest generated by it.
*/
uint256 senderBalance = balanceOf(streamId, stream.sender);
uint256 recipientBalance = balanceOf(streamId, stream.recipient);
/* Calculate the interest earned by each party for keeping `recipientBalance` in the smart contract. */
(uint256 senderInterest, uint256 recipientInterest, uint256 sablierInterest) = interestOf(
streamId,
recipientBalance
);
/*
* We add `senderInterest` to `senderBalance` to compute the net balance for the sender.
* After this, the rest of the function is similar to `withdrawFromCompoundingStreamInternal`, except
* we add the sender's share of the interest generated by `recipientBalance` to `senderBalance`.
*/
(vars.mathErr, vars.netSenderBalance) = addUInt(senderBalance, senderInterest);
require(vars.mathErr == MathError.NO_ERROR, "net sender balance calculation error");
/*
* Calculate the net withdrawal amount by subtracting `senderInterest` and `sablierInterest`.
* Because the decimal points are lost when we truncate Exponentials, the recipient will implicitly earn
* `recipientInterest` plus a tiny-weeny amount of interest, max 2e-8 in cToken denomination.
*/
(vars.mathErr, vars.recipientBalanceWithoutSenderInterest) = subUInt(recipientBalance, senderInterest);
require(vars.mathErr == MathError.NO_ERROR, "recipient balance without sender interest calculation error");
(vars.mathErr, vars.netRecipientBalance) = subUInt(vars.recipientBalanceWithoutSenderInterest, sablierInterest);
require(vars.mathErr == MathError.NO_ERROR, "net recipient balance calculation error");
/* Add the sablier interest to the earnings attributed to this cToken. */
(vars.mathErr, earnings[stream.tokenAddress]) = addUInt(earnings[stream.tokenAddress], sablierInterest);
require(vars.mathErr == MathError.NO_ERROR, "earnings addition calculation error");
/* Delete the objects from storage. */
delete streams[streamId];
delete compoundingStreamsVars[streamId];
/* Transfer the tokens to the sender and the recipient. */
IERC20 token = IERC20(stream.tokenAddress);
if (vars.netSenderBalance > 0)
require(token.transfer(stream.sender, vars.netSenderBalance), "sender token transfer failure");
if (vars.netRecipientBalance > 0)
require(token.transfer(stream.recipient, vars.netRecipientBalance), "recipient token transfer failure");
emit CancelStream(streamId, stream.sender, stream.recipient, vars.netSenderBalance, vars.netRecipientBalance);
emit PayInterest(streamId, senderInterest, recipientInterest, sablierInterest);
}
}
// File: contracts/Payroll.sol
pragma solidity 0.5.11;
/**
* @title Payroll Proxy
* @author Sablier
*/
contract Payroll is Initializable, OwnableWithoutRenounce, Exponential, GSNRecipient, GSNBouncerSignature {
/*** Storage Properties ***/
/**
* @notice Container for salary information
* @member company The address of the company which funded this salary
* @member isEntity bool true=object exists, otherwise false
* @member streamId The id of the stream in the Sablier contract
*/
struct Salary {
address company;
bool isEntity;
uint256 streamId;
}
/**
* @notice Counter for new salary ids.
*/
uint256 public nextSalaryId;
/**
* @notice Whitelist of accounts able to call the withdrawal function for a given stream so
* employees don't have to pay gas.
*/
mapping(address => mapping(uint256 => bool)) public relayers;
/**
* @notice An instance of Sablier, the contract responsible for creating, withdrawing from and cancelling streams.
*/
Sablier public sablier;
/**
* @notice The salary objects identifiable by their unsigned integer ids.
*/
mapping(uint256 => Salary) private salaries;
/*** Events ***/
/**
* @notice Emits when a salary is successfully created.
*/
event CreateSalary(uint256 indexed salaryId, uint256 indexed streamId);
/**
* @notice Emits when a compounding salary is successfully created.
*/
event CreateCompoundingSalary(uint256 indexed salaryId, uint256 indexed streamId);
/**
* @notice Emits when the employee withdraws a portion or all their pro rata share of the stream.
*/
event WithdrawFromSalary(uint256 indexed salaryId, uint256 indexed streamId);
/**
* @notice Emits when a salary is successfully cancelled and both parties get their pro rata
* share of the available funds.
*/
event CancelSalary(uint256 indexed salaryId, uint256 indexed streamId);
/**
* @dev Throws if the caller is not the company or the employee.
*/
modifier onlyCompanyOrEmployee(uint256 salaryId) {
Salary memory salary = salaries[salaryId];
(, address employee, , , , , , ) = sablier.getStream(salary.streamId);
require(
_msgSender() == salary.company || _msgSender() == employee,
"caller is not the company or the employee"
);
_;
}
/**
* @dev Throws if the caller is not the employee or an approved relayer.
*/
modifier onlyEmployeeOrRelayer(uint256 salaryId) {
Salary memory salary = salaries[salaryId];
(, address employee, , , , , , ) = sablier.getStream(salary.streamId);
require(
_msgSender() == employee || relayers[_msgSender()][salaryId],
"caller is not the employee or a relayer"
);
_;
}
/**
* @dev Throws if the id does not point to a valid salary.
*/
modifier salaryExists(uint256 salaryId) {
require(salaries[salaryId].isEntity, "salary does not exist");
_;
}
/*** Contract Logic Starts Here ***/
/**
* @notice Only called once after the contract is deployed. We ask for the owner and the signer address
* to be specified as parameters to avoid handling `msg.sender` directly.
* @dev The `initializer` modifier ensures that the function can only be called once.
* @param ownerAddress The address of the contract owner.
* @param signerAddress The address of the account able to authorise relayed transactions.
* @param sablierAddress The address of the Sablier contract.
*/
function initialize(address ownerAddress, address signerAddress, address sablierAddress) public initializer {
OwnableWithoutRenounce.initialize(ownerAddress);
GSNRecipient.initialize();
GSNBouncerSignature.initialize(signerAddress);
sablier = Sablier(sablierAddress);
nextSalaryId = 1;
}
/*** Admin ***/
/**
* @notice Whitelists a relayer to process withdrawals so the employee doesn't have to pay gas.
* @dev Throws if the caller is not the owner of the contract.
* Throws if the id does not point to a valid salary.
* Throws if the relayer is whitelisted.
* @param relayer The address of the relayer account.
* @param salaryId The id of the salary to whitelist the relayer for.
*/
function whitelistRelayer(address relayer, uint256 salaryId) external onlyOwner salaryExists(salaryId) {
require(!relayers[relayer][salaryId], "relayer is whitelisted");
relayers[relayer][salaryId] = true;
}
/**
* @notice Discard a previously whitelisted relayer to prevent them from processing withdrawals.
* @dev Throws if the caller is not the owner of the contract.
* Throws if the relayer is not whitelisted.
* @param relayer The address of the relayer account.
* @param salaryId The id of the salary to discard the relayer for.
*/
function discardRelayer(address relayer, uint256 salaryId) external onlyOwner {
require(relayers[relayer][salaryId], "relayer is not whitelisted");
relayers[relayer][salaryId] = false;
}
/*** View Functions ***/
/**
* @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the
* recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not).
*
* The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call
* calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas,
* and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the
* recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for
* replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold
* a signature over all or some of the previous values.
*
* Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code,
* values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions.
*
* {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered
* rejected. A regular revert will also trigger a rejection.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256
) external view returns (uint256, bytes memory) {
/**
* `nonce` prevents replays on RelayHub
* `getHubAddr` prevents replays in multiple RelayHubs
* `address(this)` prevents replays in multiple recipients
*/
bytes memory blob = abi.encodePacked(
relay,
from,
encodedFunction,
transactionFee,
gasPrice,
gasLimit,
nonce,
getHubAddr(),
address(this)
);
if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) == owner()) {
return _approveRelayedCall();
} else {
return _rejectRelayedCall(uint256(GSNBouncerSignatureErrorCodes.INVALID_SIGNER));
}
}
/**
* @notice Returns the salary object with all its properties.
* @dev Throws if the id does not point to a valid salary.
* @param salaryId The id of the salary to query.
* @return The salary object.
*/
function getSalary(uint256 salaryId)
public
view
salaryExists(salaryId)
returns (
address company,
address employee,
uint256 salary,
address tokenAddress,
uint256 startTime,
uint256 stopTime,
uint256 remainingBalance,
uint256 rate
)
{
company = salaries[salaryId].company;
(, employee, salary, tokenAddress, startTime, stopTime, remainingBalance, rate) = sablier.getStream(
salaries[salaryId].streamId
);
}
/*** Public Effects & Interactions Functions ***/
struct CreateSalaryLocalVars {
MathError mathErr;
}
/**
* @notice Creates a new salary funded by `msg.sender` and paid towards `employee`.
* @dev Throws if there is a math error.
* Throws if there is a token transfer failure.
* @param employee The address of the employee who receives the salary.
* @param salary The amount of tokens to be streamed.
* @param tokenAddress The ERC20 token to use as streaming currency.
* @param startTime The unix timestamp for when the stream starts.
* @param stopTime The unix timestamp for when the stream stops.
* @return The uint256 id of the newly created salary.
*/
function createSalary(address employee, uint256 salary, address tokenAddress, uint256 startTime, uint256 stopTime)
external
returns (uint256 salaryId)
{
/* Transfer the tokens to this contract. */
require(IERC20(tokenAddress).transferFrom(_msgSender(), address(this), salary), "token transfer failure");
/* Approve the Sablier contract to spend from our tokens. */
require(IERC20(tokenAddress).approve(address(sablier), salary), "token approval failure");
/* Create the stream. */
uint256 streamId = sablier.createStream(employee, salary, tokenAddress, startTime, stopTime);
salaryId = nextSalaryId;
salaries[nextSalaryId] = Salary({ company: _msgSender(), isEntity: true, streamId: streamId });
/* Increment the next salary id. */
CreateSalaryLocalVars memory vars;
(vars.mathErr, nextSalaryId) = addUInt(nextSalaryId, uint256(1));
require(vars.mathErr == MathError.NO_ERROR, "next stream id calculation error");
emit CreateSalary(salaryId, streamId);
}
/**
* @notice Creates a new compounding salary funded by `msg.sender` and paid towards `employee`.
* @dev There's a bit of redundancy between `createSalary` and this function, but one has to
* call `sablier.createStream` and the other `sablier.createCompoundingStream`, so it's not
* worth it to run DRY code.
* Throws if there is a math error.
* Throws if there is a token transfer failure.
* @param employee The address of the employee who receives the salary.
* @param salary The amount of tokens to be streamed.
* @param tokenAddress The ERC20 token to use as streaming currency.
* @param startTime The unix timestamp for when the stream starts.
* @param stopTime The unix timestamp for when the stream stops.
* @param senderSharePercentage The sender's share of the interest, as a percentage.
* @param recipientSharePercentage The sender's share of the interest, as a percentage.
* @return The uint256 id of the newly created compounding salary.
*/
function createCompoundingSalary(
address employee,
uint256 salary,
address tokenAddress,
uint256 startTime,
uint256 stopTime,
uint256 senderSharePercentage,
uint256 recipientSharePercentage
) external returns (uint256 salaryId) {
/* Transfer the tokens to this contract. */
require(IERC20(tokenAddress).transferFrom(_msgSender(), address(this), salary), "token transfer failure");
/* Approve the Sablier contract to spend from our tokens. */
require(IERC20(tokenAddress).approve(address(sablier), salary), "token approval failure");
/* Create the stream. */
uint256 streamId = sablier.createCompoundingStream(
employee,
salary,
tokenAddress,
startTime,
stopTime,
senderSharePercentage,
recipientSharePercentage
);
salaryId = nextSalaryId;
salaries[nextSalaryId] = Salary({ company: _msgSender(), isEntity: true, streamId: streamId });
/* Increment the next salary id. */
CreateSalaryLocalVars memory vars;
(vars.mathErr, nextSalaryId) = addUInt(nextSalaryId, uint256(1));
require(vars.mathErr == MathError.NO_ERROR, "next stream id calculation error");
/* We don't emit a different event for compounding salaries because we emit CreateCompoundingStream. */
emit CreateSalary(salaryId, streamId);
}
struct CancelSalaryLocalVars {
MathError mathErr;
uint256 netCompanyBalance;
}
/**
* @notice Withdraws from the contract to the employee's account.
* @dev Throws if the id does not point to a valid salary.
* Throws if the caller is not the employee or a relayer.
* Throws if there is a token transfer failure.
* @param salaryId The id of the salary to withdraw from.
* @param amount The amount of tokens to withdraw.
* @return bool true=success, false otherwise.
*/
function withdrawFromSalary(uint256 salaryId, uint256 amount)
external
salaryExists(salaryId)
onlyEmployeeOrRelayer(salaryId)
returns (bool success)
{
Salary memory salary = salaries[salaryId];
success = sablier.withdrawFromStream(salary.streamId, amount);
emit WithdrawFromSalary(salaryId, salary.streamId);
}
/**
* @notice Cancels the salary and transfers the tokens back on a pro rata basis.
* @dev Throws if the id does not point to a valid salary.
* Throws if the caller is not the company or the employee.
* Throws if there is a token transfer failure.
* @param salaryId The id of the salary to cancel.
* @return bool true=success, false otherwise.
*/
function cancelSalary(uint256 salaryId)
external
salaryExists(salaryId)
onlyCompanyOrEmployee(salaryId)
returns (bool success)
{
Salary memory salary = salaries[salaryId];
/* We avoid storing extraneous data twice, so we read the token address from Sablier. */
(, address employee, , address tokenAddress, , , , ) = sablier.getStream(salary.streamId);
uint256 companyBalance = sablier.balanceOf(salary.streamId, address(this));
/**
* The company gets all the money that has not been streamed yet, plus all the interest earned by what's left.
* Not all streams are compounding and `companyBalance` coincides with `netCompanyBalance` then.
*/
CancelSalaryLocalVars memory vars;
if (!sablier.isCompoundingStream(salary.streamId)) {
vars.netCompanyBalance = companyBalance;
} else {
uint256 employeeBalance = sablier.balanceOf(salary.streamId, employee);
(uint256 companyInterest, , ) = sablier.interestOf(salary.streamId, employeeBalance);
(vars.mathErr, vars.netCompanyBalance) = addUInt(companyBalance, companyInterest);
require(vars.mathErr == MathError.NO_ERROR, "net company balance calculation error");
}
/* Delete the salary object to save gas. */
delete salaries[salaryId];
success = sablier.cancelStream(salary.streamId);
/* Transfer the tokens to the company. */
if (vars.netCompanyBalance > 0)
require(
IERC20(tokenAddress).transfer(salary.company, vars.netCompanyBalance),
"company token transfer failure"
);
emit CancelSalary(salaryId, salary.streamId);
}
} | Cancels the stream and transfers the tokens back on a pro rata basis. The stream and compounding stream vars objects get deleted to save gas and optimise contract storage. Throws if there is a token transfer failure./ | function cancelStreamInternal(uint256 streamId) internal {
Types.Stream memory stream = streams[streamId];
uint256 senderBalance = balanceOf(streamId, stream.sender);
uint256 recipientBalance = balanceOf(streamId, stream.recipient);
delete streams[streamId];
IERC20 token = IERC20(stream.tokenAddress);
if (recipientBalance > 0)
require(token.transfer(stream.recipient, recipientBalance), "recipient token transfer failure");
if (senderBalance > 0) require(token.transfer(stream.sender, senderBalance), "sender token transfer failure");
emit CancelStream(streamId, stream.sender, stream.recipient, senderBalance, recipientBalance);
}
| 5,427,281 |
./full_match/43114/0x697fc3000F2C286634D8f5468da728db9e183BF4/sources/contracts/Swapper.sol | get asset Price from Dex (Price for 1 wei) 10 ^ 36 | function getTokenPrice(address asset) public view returns(uint256, uint256) {
if(stableToken == address(0x0)) {
return (0, 0);
}
uint256 stableDecimal = IERC20Minimal(stableToken).decimals();
if(asset == stableToken) {
return (10 ** (36 - stableDecimal), stableDecimal);
}
address[] memory path = getPath(asset, false);
uint pathLength = path.length;
if(pathLength == 0) {
return (0, 0);
}
uint256 assetDecimal = (asset == address(0x0)) ? 18 : IERC20Minimal(asset).decimals();
uint256 stableAmountFor1Asset = uniswapV2Router.getAmountsOut(10 ** assetDecimal, path)[pathLength - 1];
return (stableAmountFor1Asset.mul(10 ** (36 - stableDecimal - assetDecimal)), assetDecimal);
}
| 4,532,831 |
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(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 MUL487(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 DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV156(a, b, "SafeMath: division by zero");
}
function DIV156(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 MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD860(a, b, "SafeMath: modulo by zero");
}
function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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);
}
function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value));
}
function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value));
}
function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// 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.ALLOWANCE946(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value));
}
function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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");
}
}
}
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;
}
function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS837(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;
}
}
function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
}
function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(uint256(value)));
}
function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(uint256(value)));
}
function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(uint256(value)));
}
function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT524(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(value));
}
function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(value));
}
function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(value));
}
function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT524(set._inner, index));
}
}
contract Initializable {
bool private initialized;
bool private initializing;
modifier INITIALIZER933() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR543() 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 ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
}
function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING
}
function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA356() 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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
__OWNABLE_INIT_UNCHAINED19();
}
function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER195();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED637(address(0), msgSender);
}
function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER691() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED637(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED637(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
interface INBUNIERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
event LOG470(string log); //inject NONSTANDARD NAMING
}
library console {
address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address243;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG714() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log()"));
}
function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOG714(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// HDCore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract HdcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HdCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block.
uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The HDCORE TOKEN!
INBUNIERC20 public hdcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock));
}
// Returns averge fees in this epoch
function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING
address indexed user,
uint256 indexed pid,
uint256 amount
);
event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING
function INITIALIZE896( //inject NONSTANDARD NAMING
INBUNIERC20 _hdcore
) public INITIALIZER933 {
OwnableUpgradeSafe.__OWNABLE_INIT503();
DEV_FEE = 724;
hdcore = _hdcore;
devaddr = msg.sender;
contractStartBlock = block.number;
_superAdmin = msg.sender;
}
function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function ADD659( //inject NONSTANDARD NAMING
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.ADD659(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accHdcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's HDCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SET408( //inject NONSTANDARD NAMING
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING
uint256 _pid,
bool _withdrawable
) public ONLYOWNER691 {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 7.24%
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
uint16 DEV_FEE;
function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending HDCOREs on frontend.
function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHdcorePerShare = pool.accHdcorePerShare;
return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING
console.LOG714("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.ADD659(UPDATEPOOL374(pid));
}
pendingRewards = pendingRewards.SUB877(allRewards);
}
// ----
// Function that adds pending rewards, called by the HDCORE token.
// ----
uint256 private hdcoreBalance;
function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING
uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance);
if(newRewards > 0) {
hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.ADD659(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.BALANCEOF536(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.DIV156(totalAllocPoint); // we can do this because pools are only mass updated
uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000);
uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee);
pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659(
hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply)
);
}
// Deposit tokens to HdcoreVault for HDCORE allocation.
function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit APPROVAL172(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount);
_WITHDRAW26(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from HdcoreVault.
function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
_WITHDRAW26(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed
if(_amount > 0) {
user.amount = user.amount.SUB877(_amount);
pool.token.SAFETRANSFER239(address(to), _amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit WITHDRAW483(to, _pid, _amount);
}
function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
}
function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING
if(user.amount == 0) return;
uint256 pending = user
.amount
.MUL487(pool.accHdcorePerShare)
.DIV156(1e12)
.SUB877(user.rewardDebt);
if(pending > 0) {
SAFEHDCORETRANSFER939(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked
function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).APPROVE926(contractAddress, _amount);
}
function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.SAFETRANSFER239(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs.
function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
if(_amount == 0) return;
uint256 hdcoreBal = hdcore.BALANCEOF536(address(this));
if (_amount > hdcoreBal) {
console.LOG714("transfering out for to person:", _amount);
console.LOG714("Balance of this address is :", hdcoreBal);
hdcore.TRANSFER353(_to, hdcoreBal);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
} else {
hdcore.TRANSFER353(_to, _amount);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
SAFEHDCORETRANSFER939(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing HDCORE governance token holders to do this functions.
function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING
devaddr = _devaddr;
}
address private _superAdmin;
event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING
return _superAdmin;
}
modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING
require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
emit SUPERADMINTRANSFERED362(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SUPERADMINTRANSFERED362(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | inject NONSTANDARD NAMING | function LOG714(address p0, address p1, bool p2, string memory p3) internal view { | 14,087,976 |
pragma solidity ^0.5.15;
interface IERC20 {
function TOTALSUPPLY265() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF676(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER585(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE478(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE401(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM799(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER297(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL288(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER981() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA870() internal view 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;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED51(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER981();
emit OWNERSHIPTRANSFERRED51(address(0), _owner);
}
function OWNER52() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER947() { //inject NONSTANDARD NAMING
require(ISOWNER855(), "Ownable: caller is not the owner");
_;
}
function ISOWNER855() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER981() == _owner;
}
function RENOUNCEOWNERSHIP936() public ONLYOWNER947 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED51(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP177(address newOwner) public ONLYOWNER947 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP636(newOwner);
}
function _TRANSFEROWNERSHIP636(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED51(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY265() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF676(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER585(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER399(_MSGSENDER981(), recipient, amount);
return true;
}
function ALLOWANCE478(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE401(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, amount);
return true;
}
function TRANSFERFROM799(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER399(sender, recipient, amount);
_APPROVE768(sender, _MSGSENDER981(), _allowances[sender][_MSGSENDER981()].SUB171(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE254(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].ADD125(addedValue));
return true;
}
function DECREASEALLOWANCE775(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].SUB171(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER399(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB171(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD125(amount);
emit TRANSFER297(sender, recipient, amount);
}
function _MINT552(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD125(amount);
_balances[account] = _balances[account].ADD125(amount);
emit TRANSFER297(address(0), account, amount);
}
function _BURN908(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB171(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB171(amount);
emit TRANSFER297(account, address(0), amount);
}
function _APPROVE768(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
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 APPROVAL288(owner, spender, amount);
}
function _BURNFROM359(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN908(account, amount);
_APPROVE768(account, _MSGSENDER981(), _allowances[account][_MSGSENDER981()].SUB171(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME677() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL955() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS596() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD125(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB171(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB171(a, b, "SafeMath: subtraction overflow");
}
function SUB171(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 MUL207(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV619(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV619(a, b, "SafeMath: division by zero");
}
function DIV619(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;
return c;
}
function MOD550(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD550(a, b, "SafeMath: modulo by zero");
}
function MOD550(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT651(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE339(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE156(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER644(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFER585.selector, to, value));
}
function SAFETRANSFERFROM18(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFERFROM799.selector, from, to, value));
}
function SAFEAPPROVE229(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE478(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, value));
}
function SAFEINCREASEALLOWANCE497(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE478(address(this), spender).ADD125(value);
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE975(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE478(address(this), spender).SUB171(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN428(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT651(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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");
}
}
}
interface Controller {
function WITHDRAW158(address, uint) external; //inject NONSTANDARD NAMING
function BALANCEOF676(address) external view returns (uint); //inject NONSTANDARD NAMING
function EARN532(address, uint) external; //inject NONSTANDARD NAMING
function REWARDS630() external view returns (address); //inject NONSTANDARD NAMING
}
// vault1111 111111111111
// abi1111: https://github.com/ystar-foundation/YstarFarming/blob/master/Vault/abi/vault.json
contract Vault {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
IERC20 public YFToken; // YF1111
uint public min = 9500;
uint public constant max986 = 10000; //inject NONSTANDARD NAMING
uint public earnLowerlimit; //1111111111111earn
address public governance;
address public controller;
struct Player {
uint256 stake; // 1111
uint256 payout; // 11
uint256 total_out; // 1111111
}
mapping(address => Player) public player_; // (player => data) player data
struct Global {
uint256 total_stake; // 11111
uint256 total_out; // 11111
uint256 earnings_per_share; // 1111
}
mapping(uint256 => Global) public global_; // (global => data) global data
mapping (address => uint256) public deposittime;
uint256 constant internal magnitude720 = 10**40; // 1014011 //inject NONSTANDARD NAMING
address constant public yf82 = address(0x96F9632b25f874769969ff91219fCCb6ceDf26D2); //inject NONSTANDARD NAMING
string public getName;
constructor (address _token, uint256 _earnLowerlimit) public {
token = IERC20(_token);
getName = string(abi.encodePacked("yf:Vault:", ERC20Detailed(_token).NAME677()));
earnLowerlimit = _earnLowerlimit*1e18;
YFToken = IERC20(yf82);
governance = tx.origin;
controller = 0xcC8d36211374a08fC61d74ed2E48e22b922C9D7C;
}
function BALANCE265() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF676(address(this))
.ADD125(Controller(controller).BALANCEOF676(address(token)));
}
function SETMIN245(uint _min) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
min = _min;
}
// 11111111111111111111
function SETGOVERNANCE992(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
// 1111token
function SETTOKEN102(address _token) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
token = IERC20(_token);
}
// 1111111111111111111
function SETCONTROLLER604(address _controller) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
function SETEARNLOWERLIMIT476(uint256 _earnLowerlimit) public{ //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
// Custom logic in here for how much the vault allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
// 11111111111
// 111111111111111111111
function AVAILABLE23() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF676(address(this)).MUL207(min).DIV619(max986); // balance*min/max 1111111111111111111
}
// 11111Strategy1111111111111 vault->controller->strategy
function EARN532() public { //inject NONSTANDARD NAMING
uint _bal = AVAILABLE23(); // 1111111111111111111111
token.SAFETRANSFER644(controller, _bal); // 1111111
Controller(controller).EARN532(address(token), _bal); // 11111Strategy111111
}
// 11 111111
function DEPOSIT245(uint amount) external { //inject NONSTANDARD NAMING
// 111111111111111111appove1111111111111
token.SAFETRANSFERFROM18(msg.sender, address(this), amount);
// 1111111111
player_[msg.sender].stake = player_[msg.sender].stake.ADD125(amount);
// 11111110
if (global_[0].earnings_per_share != 0) {
player_[msg.sender].payout = player_[msg.sender].payout.ADD125(
global_[0].earnings_per_share.MUL207(amount).SUB171(1).DIV619(magnitude720).ADD125(1) // (((earnings_per_share*amount)-1)/magnitude)+1
);
}
// 1111111111
global_[0].total_stake = global_[0].total_stake.ADD125(amount);
// 111111111111111111111111111111111111111111111
if (token.BALANCEOF676(address(this)) > earnLowerlimit){
EARN532();
}
// 11111111
deposittime[msg.sender] = now;
}
// No rebalance implementation for lower fees and faster swaps
// 11
function WITHDRAW158(uint amount) external { //inject NONSTANDARD NAMING
CLAIM365(); // 111111111111
require(amount <= player_[msg.sender].stake, "!balance");
uint r = amount;
// Check balance
uint b = token.BALANCEOF676(address(this));
if (b < r) { // 11vault111111111111111111111Strategy11111111111
uint _withdraw = r.SUB171(b);
Controller(controller).WITHDRAW158(address(token), _withdraw); // 11
uint _after = token.BALANCEOF676(address(this));
uint _diff = _after.SUB171(b);
if (_diff < _withdraw) { // 111111111111111111111vault111111
r = b.ADD125(_diff);
}
}
// 111111111111111111111
player_[msg.sender].payout = player_[msg.sender].payout.SUB171(
global_[0].earnings_per_share.MUL207(amount).DIV619(magnitude720)
);
// 1111111111111
player_[msg.sender].stake = player_[msg.sender].stake.SUB171(amount);
global_[0].total_stake = global_[0].total_stake.SUB171(amount);
// 1111111111
token.SAFETRANSFER644(msg.sender, r);
}
// Strategy.harvest 111111
function MAKE_PROFIT788(uint256 amount) public { //inject NONSTANDARD NAMING
require(amount > 0, "not 0");
YFToken.SAFETRANSFERFROM18(msg.sender, address(this), amount); // 1111111111111110%1111190%1111111
global_[0].earnings_per_share = global_[0].earnings_per_share.ADD125(
amount.MUL207(magnitude720).DIV619(global_[0].total_stake)
);
global_[0].total_out = global_[0].total_out.ADD125(amount);
}
// 11111111
function CAL_OUT246(address user) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _cal = global_[0].earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720);
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.SUB171(player_[user].payout);
}
}
// 11111111111111111111111111.11111111111harvest1111111111
function CAL_OUT_PENDING918(uint256 _pendingBalance,address user) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _earnings_per_share = global_[0].earnings_per_share.ADD125(
_pendingBalance.MUL207(magnitude720).DIV619(global_[0].total_stake)
);
uint256 _cal = _earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720);
_cal = _cal.SUB171(CAL_OUT246(user));
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.SUB171(player_[user].payout);
}
}
// 111111
function CLAIM365() public { //inject NONSTANDARD NAMING
uint256 out = CAL_OUT246(msg.sender);
player_[msg.sender].payout = global_[0].earnings_per_share.MUL207(player_[msg.sender].stake).DIV619(magnitude720);
player_[msg.sender].total_out = player_[msg.sender].total_out.ADD125(out);
if (out > 0) {
uint256 _depositTime = now - deposittime[msg.sender];
if (_depositTime < 1 days){ // deposit in 24h
uint256 actually_out = _depositTime.MUL207(out).MUL207(1e18).DIV619(1 days).DIV619(1e18);
uint256 to_team = out.SUB171(actually_out);
YFToken.SAFETRANSFER644(Controller(controller).REWARDS630(), to_team);
out = actually_out;
}
YFToken.SAFETRANSFER644(msg.sender, out);
}
}
} | inject NONSTANDARD NAMING | function APPROVE401(address spender, uint256 amount) external returns (bool); | 12,634,594 |
pragma solidity ^0.5.0;
contract Charity {
enum CharityStatus {UNVERIFIED, VERIFIED, REJECTED}
enum CampaignStatus {ONGOING, ENDED}
struct charity {
address charityOwner;
string charityName;
string charityAddress;
string contactNumber;
string description;
string pictureURL;
string verificationLink;
CharityStatus charityStatus;
address[] donors;
}
struct campaign {
uint256 charityId;
string campaignName;
string description;
string pictureURL;
uint256 targetDonation;
uint256 currentDonation;
uint256 noOfDonors;
uint256 startDate;
uint256 endDate;
CampaignStatus campaignStatus;
}
address contractOwner = msg.sender;
mapping(uint256 => bool) isVerifiedCharity;
mapping(uint256 => charity) charities;
mapping(address => uint256) charityAddressIdMap;
mapping(address => charity) charityAddressMap;
mapping(address => bool) charityOwnerRegistered;
address[] donors;
uint256 noOfCharities = 0;
uint contractMoney = 0;
uint256 charityRegFee = 5 * 10**17; // Reg fee is 0.5 ether, 1 ether is 10**18 wei
mapping(uint256 => bool) isOngoingCampaign;
mapping(uint256 => campaign) campaigns;
uint256 noOfCampaigns = 0;
uint256 noOfReturns = 0;
modifier onlyOwner(address caller) {
require(caller == contractOwner, "Caller is not contract owner");
_;
}
// This will be the modifier that checks whether the function call is done by the Charity itself.
modifier onlyVerifiedCharity(address caller) {
require(
isVerifiedCharity[charityAddressIdMap[caller]],
"Caller is not a valid charity"
);
_;
}
// This will be the modifier that checks whether the function call is done by the Charity or contract owner itself.
modifier onlyVerifiedCharityOrOwner(address caller) {
require(
isVerifiedCharity[charityAddressIdMap[caller]] || caller == contractOwner,
"Caller is not a valid charity nor contract owner"
);
_;
}
/*
* This will be the function that check the address type
* Parameters of this function will include address inputAddress
* This function assumes all input address are either contract, charity, or donor
*/
function checkAddressType(
address inputAddress
)
public
view
returns (string memory)
{
if (inputAddress == contractOwner) {
return "CONTRACT";
} else if (charityOwnerRegistered[inputAddress] == true) {
return "CHARITYOWNER";
} else {
return "DONOR";
}
}
/*
* This will be the function that allows contract owner to withdraw money
* There will be no parameters for this function
*/
function withdrawMoney()
public
onlyOwner(msg.sender)
{
require(contractMoney >= 3 * charityRegFee, "Current money is less than 3 * charity register fee");
address payable recipient = address(uint160(address(this)));
recipient.transfer(contractMoney);
contractMoney = 0;
}
/*
* This fallback function is to make contract address able to receive/make payments
*/
function() external payable { }
/*
* This will be the payable function to register the charity
* Parameters will be string charityName, string charityAddress, string contactNumber, string description and string pictureURL
* Need at least 0.5 ether to register
*/
function registerCharity(
string memory charityName,
string memory charityAddress,
string memory contactNumber,
string memory description,
string memory pictureURL
)
public payable
returns (uint256 charityId) {
require(
charityOwnerRegistered[msg.sender] == false,
"This address has registered another charity already"
);
require(
msg.value >= charityRegFee,
"Need at least 0.5 ether to register a charity"
);
contractMoney = contractMoney + msg.value;
charityId = noOfCharities++;
charity memory newCharity =
charity(
msg.sender,
charityName,
charityAddress,
contactNumber,
description,
pictureURL,
"",
CharityStatus.UNVERIFIED,
donors
);
charities[charityId] = newCharity;
charityAddressIdMap[msg.sender] = charityId;
isVerifiedCharity[charityId] = false;
charityOwnerRegistered[msg.sender] = true;
address payable recipient = address(uint160(contractOwner));
recipient.transfer(msg.value);
return charityId;
}
/*
* This will be the function for contract owner to verify the charity
* Parameters will be uint charityId, string verification
*/
function verifyCharity(
uint256 charityId, string memory verificationLink
)
public
onlyOwner(msg.sender)
{
require(msg.sender == contractOwner, "Caller is not contract owner");
require(charityId < noOfCharities, "Invalid charity id");
require(
charities[charityId].charityStatus == CharityStatus.UNVERIFIED,
"Charity has been verified or rejected"
);
require(
isVerifiedCharity[charityId] == false,
"Charity has been verified"
);
charities[charityId].charityStatus = CharityStatus.VERIFIED;
charities[charityId].verificationLink = verificationLink;
isVerifiedCharity[charityId] = true;
}
/*
* This will be the function for contract owner to reject the charity
* Parameters will be uint charityId, string verification
*/
function rejectCharity(
uint256 charityId
)
public
onlyOwner(msg.sender)
{
require(msg.sender == contractOwner, "Caller is not contract owner");
require(charityId < noOfCharities, "Invalid charity id");
require(
charities[charityId].charityStatus == CharityStatus.UNVERIFIED,
"Charity has been verified or rejected"
);
require(
isVerifiedCharity[charityId] == false,
"Charity has been verified"
);
charities[charityId].charityStatus = CharityStatus.REJECTED;
}
/*
* This will be the function for contract owner to revoke the charity
* Parameters will be uint charityId, string verification
*/
function revokeCharity(
uint256 charityId
)
public
onlyOwner(msg.sender)
{
require(charityId < noOfCharities, "Invalid charity id");
require(
charities[charityId].charityStatus == CharityStatus.VERIFIED,
"Charity is not a verified charity"
);
charities[charityId].charityStatus = CharityStatus.REJECTED;
}
/*
* This will be the function that charities call to create a campaign.
* Parameters of this function will include string campaignName, string description, string pictureURL, uint targetDonation (of the campaign), uint startDate (of the campaign), uint endDate (of the campaign)
*/
function createCampaign(
string memory campaignName,
string memory description,
string memory pictureURL,
uint256 targetDonation,
uint256 startDate,
uint256 endDate
)
public
onlyVerifiedCharity(msg.sender)
returns (uint256 campaignId)
{
campaignId = noOfCampaigns++;
uint256 charityId = charityAddressIdMap[msg.sender];
campaign memory newCampaign =
campaign(
charityId,
campaignName,
description,
pictureURL,
targetDonation,
0,
0,
startDate,
endDate,
CampaignStatus.ONGOING
);
campaigns[campaignId] = newCampaign;
isOngoingCampaign[campaignId] = true;
return campaignId;
}
/*
* This will be the function that charities or contract owner call to end an ongoing campaign.
* Parameters of this function will include uint campaignId
*/
function endCampaign(
uint256 campaignId
)
public
onlyVerifiedCharityOrOwner(msg.sender)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
require(isOngoingCampaign[campaignId], "Campaign is not ongoing");
require(
msg.sender ==
charities[campaigns[campaignId].charityId].charityOwner ||
msg.sender == contractOwner,
"Caller is not authorized for this operation"
);
campaigns[campaignId].campaignStatus = CampaignStatus.ENDED;
isOngoingCampaign[campaignId] = false;
}
/*
* This will be the getter function that everyone can call to check the charity address.
* Parameters of this function will include uint charityId
*/
function getCharityOwner(
uint256 charityId
)
public
view
returns (address)
{
require(charityId < noOfCharities, "Invalid charity id");
return charities[charityId].charityOwner;
}
/*
* This will be the getter function that everyone can call to check the charity id.
* Parameters of this function will include address inputAddress
*/
function getCharityIdByAddress(
address inputAddress
)
public
view
returns (uint256)
{
require(
charityOwnerRegistered[inputAddress] == true,
"Address not owner of any charity"
);
uint256 charityIdByAddress = charityAddressIdMap[inputAddress];
return charityIdByAddress;
}
/*
* This will be the getter function that everyone can call to check the charity name.
* Parameters of this function will include uint charityId
*/
function getCharityName(
uint256 charityId
)
public
view
returns (string memory)
{
require(charityId < noOfCharities, "Invalid charity id");
return charities[charityId].charityName;
}
/*
* This will be the getter function that everyone can call to check the charity pictureURL.
* Parameters of this function will include uint charityId
*/
function getCharityPictureURL(
uint256 charityId
)
public
view
returns (string memory)
{
require(charityId < noOfCharities, "Invalid charity id");
return charities[charityId].pictureURL;
}
/*
* This will be the getter function that everyone can call to check the charity pictureURL.
* Parameters of this function will include address inputAddress
*/
function getCharityPictureURLByAddress(address inputAddress)
public
view
returns (string memory)
{
require(
charityOwnerRegistered[inputAddress] == true,
"Address not owner of any charity"
);
uint256 charityIdByAddress = charityAddressIdMap[inputAddress];
return charities[charityIdByAddress].pictureURL;
}
/*
* This will be the getter function that everyone can call to check the charity description.
* Parameters of this function will include uint charityId
*/
function getCharityDescription(
uint256 charityId
)
public
view
returns (string memory)
{
require(charityId < noOfCharities, "Invalid charity id");
return charities[charityId].description;
}
/*
* This will be the getter function that everyone can call to check the charity status.
* Parameters of this function will include uint charityId
*/
function getCharityStatus(
uint256 charityId
)
public
view
returns (CharityStatus)
{
require(charityId < noOfCharities, "Invalid charity id");
return charities[charityId].charityStatus;
}
/*
* This will be the getter function that everyone can call to check the charity status.
* Parameters of this function will include address inputAddress
*/
function getCharityStatusByAddress(
address inputAddress
)
public
view
returns (CharityStatus)
{
require(
charityOwnerRegistered[inputAddress] == true,
"Address not owner of any charity"
);
uint256 charityIdByAddress = charityAddressIdMap[inputAddress];
return charities[charityIdByAddress].charityStatus;
}
/*
* This will be the getter function that everyone can call to get the charity contact number.
* Parameters of this function will include uint charityId
*/
function getCharityContactNumber(
uint256 charityId
)
public
view
returns (string memory)
{
require(charityId < noOfCharities, "Invalid charity id");
return charities[charityId].contactNumber;
}
/*
* This will be the getter function that everyone can call to get the charity contact address.
* Parameters of this function will include uint charityId
*/
function getCharityContactAddress(
uint256 charityId
)
public
view
returns (string memory)
{
require(charityId < noOfCharities, "Invalid charity id");
return charities[charityId].charityAddress;
}
/*
* This will be the getter function that everyone can call to get the charity verification Link.
* Parameters of this function will include uint charityId
*/
function getCharityVerificationLink(
uint256 charityId
)
public
view
returns (string memory)
{
require(charityId < noOfCharities, "Invalid charity id");
return charities[charityId].verificationLink;
}
/*
* This will be the getter function that everyone can call to get the total amounts of the charities.
* There will be no parameters for this function
*/
function getNoOfCharities()
public
view
returns (uint256)
{
return noOfCharities;
}
/*
* This will be the getter function that everyone can call to check the campaign's charityId.
* Parameters of this function will include uint campaignId
*/
function getCampaignCharity(
uint256 campaignId
)
public
view
returns (uint256)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].charityId;
}
/*
* This will be the getter function that everyone can call to check the campaign name.
* Parameters of this function will include uint campaignId
*/
function getCampaignName(
uint256 campaignId
)
public
view
returns (string memory)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].campaignName;
}
/*
* This will be the getter function that everyone can call to check the campaign description.
* Parameters of this function will include uint campaignId
*/
function getCampaignDescription(
uint256 campaignId
)
public
view
returns (string memory)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].description;
}
/*
* This will be the getter function that everyone can call to check the campaign pictureURL.
* Parameters of this function will include uint campaignId
*/
function getCampaignPictureURL(
uint256 campaignId
)
public
view
returns (string memory)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].pictureURL;
}
/*
* This will be the getter function that everyone can call to check the campaign targetDonation.
* Parameters of this function will include uint campaignId
*/
function getCampaignTargetDonation(
uint256 campaignId
)
public
view
returns (uint256)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].targetDonation;
}
/*
* This will be the getter function that everyone can call to check the campaign currentDonation.
* Parameters of this function will include uint campaignId
*/
function getCampaignCurrentDonation(
uint256 campaignId
)
public
view
returns (uint256)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].currentDonation;
}
/*
* This will be the getter function that everyone can call to check the campaign noOfDonors.
* Parameters of this function will include uint campaignId
*/
function getCampaignNoOfDonors(
uint256 campaignId
)
public
view
returns (uint256)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].noOfDonors;
}
/*
* This will be the getter function that everyone can call to check the campaign startDate.
* Parameters of this function will include uint campaignId
*/
function getCampaignStartDate(
uint256 campaignId
)
public
view
returns (uint256)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].startDate;
}
/*
* This will be the getter function that everyone can call to check the campaign endDate.
* Parameters of this function will include uint campaignId
*/
function getCampaignEndDate(
uint256 campaignId
)
public
view
returns (uint256)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].endDate;
}
/*
* This will be the getter function that everyone can call to check the campaign status.
* Parameters of this function will include uint campaignId
*/
function getCampaignStatus(
uint256 campaignId
)
public
view
returns (CampaignStatus)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
return campaigns[campaignId].campaignStatus;
}
/*
* This will be the getter function that everyone can call to get the total amounts of the campaigns.
* There will be no parameters fot this function
*/
function getNoOfCampaigns()
public
view
returns (uint256)
{
return noOfCampaigns;
}
/*
*This will be the getter function that everyone can call to check the status of the campaign.
* Parameters of this function will include uint campaignId
*/
function isStatusComplete(
uint256 campaignId
)
public
view
returns (bool)
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
if (campaigns[campaignId].campaignStatus == CampaignStatus.ENDED) {
return true;
}
return false;
}
/*
*This will be the getter function that everyone can call to check if the campagin is valid
* Parameters of this function will include uint campaignId
*/
function checkValidCampaign(
uint256 campaignId
)
public
view
returns (bool)
{
if (campaignId < noOfCampaigns) {
return true;
}
return false;
}
/*
* This will be the function that updates the campaign's currentDonation
* Parameters of this function will include uint campaignId and uint newDonation
*/
function updateCampaignCurrentDonation(
uint256 campaignId,
uint256 newDonation
)
public
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
uint256 newAmount = campaigns[campaignId].currentDonation + newDonation;
campaigns[campaignId].currentDonation = newAmount;
}
/*
* This will be the function that updates the campaign's noOfDonors
* Parameters of this function will include uint campaignId
*/
function addCampaignDonor(
uint256 campaignId
)
public
{
require(campaignId < noOfCampaigns, "Invalid campaign id");
uint256 newNumber = campaigns[campaignId].noOfDonors + 1;
campaigns[campaignId].noOfDonors = newNumber;
}
/*
* This will be the function that returns the charity's donors
* Parameters of this function will include uint campaignId
*/
function getDonors(
uint256 charityId
)
public
view
returns(address[] memory)
{
address[] memory donorList = charities[charityId].donors;
return donorList;
}
/*
* This will be the function that get charity register fee
* There will be no parameters for this function
*/
function getRegFee() public view returns(uint256) {
return charityRegFee;
}
/*
* This will be the function to get contract's owner
* There will be no parameters for this function
*/
function getContractOwner() public view returns (address) {
return contractOwner;
}
/*
* This will be the function to check if donor has donated to charity before
* Parameters of this function will include address donor, uint charityId
*/
function checkCharityDonor(
address donor,
uint256 charityId
)
public
view
returns (bool)
{
uint length = charities[charityId].donors.length;
for (uint i = 0; i < length; i++) {
if(charities[charityId].donors[i] == donor) {
return true;
}
}
return false;
}
/*
* This will be the function to add a new donor to charity
* Parameters of this function will include address donor, uint charityId
*/
function addCharityDonor(
address donor,
uint256 charityId
)
public
{
charities[charityId].donors.push(donor);
}
} | This will be the function that charities call to create a campaign. Parameters of this function will include string campaignName, string description, string pictureURL, uint targetDonation (of the campaign), uint startDate (of the campaign), uint endDate (of the campaign)/ | function createCampaign(
string memory campaignName,
string memory description,
string memory pictureURL,
uint256 targetDonation,
uint256 startDate,
uint256 endDate
)
public
onlyVerifiedCharity(msg.sender)
returns (uint256 campaignId)
{
campaignId = noOfCampaigns++;
uint256 charityId = charityAddressIdMap[msg.sender];
campaign memory newCampaign =
campaign(
charityId,
campaignName,
description,
pictureURL,
targetDonation,
0,
0,
startDate,
endDate,
CampaignStatus.ONGOING
);
campaigns[campaignId] = newCampaign;
isOngoingCampaign[campaignId] = true;
return campaignId;
}
| 6,449,569 |
./partial_match/3/0xf86a5BF508D8312bcD8FE515a00808BC37b82CE5/sources/TestToken.sol | Tranfer tokens from sender to this contractERC20(Sedo).transferFrom(msg.sender, SedoX, SedoAmount); Calculate sedox to transfer by the swapRatio;uint256 fee = SedoAmount / 100; Transfer amount minus fees to sender | function Swap(uint256 SedoAmount) public{
address Sedo = parentAddress;
address SedoX = address(this);
ERC20(Sedo).transfer(SedoX, SedoAmount);
uint256 SedoxAmmount = SedoAmount / defaultSwapRatio;
ERC20(SedoX).transfer(msg.sender, SedoxAmmount);
}
| 5,102,874 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity =0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import './FeeExchanger.sol';
import '../interface/IFeeDistributor.sol';
/**
* @author Asaf Silman
* @title FeeExchanger using Sushiswap
* @dev This contract is upgradable and should be deployed using Openzeppelin upgrades
* @notice Exchanges fees for `outputToken` and forwards to `outputAddress`
*/
contract SushiswapExchanger is FeeExchanger {
using SafeERC20Upgradeable for IERC20Upgradeable;
// Sushiswap router is implmenented using the uniswap interface
IUniswapV2Router02 private _sushiswapRouter;
address[] private _path;
string constant _name = "Sushiswap Exchanger";
/**
* @notice Initialises the Sushiswap Exchanger contract.
* @dev Most of the initialisation is done as part of the `FeeExchanger` initialisation.
* @dev This method sets the internal sushiswap router address.
* @dev This method also initialises the router path.
* @param routerAddress The address of the sushiswap router.
* @param inputToken The token which the protocol fees are generated in. This should set to the WETH address.
* @param outputToken The token which this contract will exchange fees into.
* @param outputAddress The address where fees will be redirected to.
*/
function initialize(IUniswapV2Router02 routerAddress, IERC20Upgradeable inputToken, IERC20Upgradeable outputToken, address outputAddress) public initializer {
FeeExchanger.__FeeExchanger_init(inputToken, outputToken, outputAddress);
_sushiswapRouter = routerAddress;
_path = new address[](2);
_path[0] = address(inputToken);
_path[1] = address(outputToken);
}
/**
* @notice Exchanges fees on sushiswap
* @dev This method validates the minAmountOut was transfered to the output address.
* @dev The expiration time is hardcoded to 1800 seconds, or 30 minutes.
* @dev This method can only be called by an approved exchanger, see FeeExchanger.sol for more info.
* @dev This method can be static called to analyse the output amount of tokens at a given time.
* @param amountIn The input amount of fees to swap.
* @param minAmountOut The minimum output amount of tokens to receive after the swap has executed.
* @return The amount of output token which was exchanged
*/
function exchange(uint256 amountIn, uint256 minAmountOut) nonReentrant onlyExchanger external override returns (uint256) {
require(FeeExchanger._inputToken.balanceOf(address(this)) >= amountIn, "FE: AMOUNT IN");
// Approve input token for swapping
FeeExchanger._inputToken.safeIncreaseAllowance(address(_sushiswapRouter), amountIn);
uint256 balance0 = FeeExchanger._outputToken.balanceOf(address(this));
// Swap tokens using sushi
_sushiswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
amountIn,
minAmountOut,
_path,
address(this),
block.timestamp + 1800
);
uint256 balance1 = FeeExchanger._outputToken.balanceOf(address(this));
uint256 amountOut = balance1 - balance0;
// Approve output token to call `burn` on feeDistributor
// Note, burn will transfer the entire balance of outputToken
FeeExchanger._outputToken.safeIncreaseAllowance(address(FeeExchanger._outputAddress), balance1);
// Deposit output token via `burn`
IFeeDistributor(FeeExchanger._outputAddress).burn(address(FeeExchanger._outputToken));
emit TokenExchanged(amountIn, amountOut, _name);
return amountOut;
}
/**
* @notice Updates the swapping path for the router.
* @dev The first element of the path must be the input token.
* @dev The last element of the path must be the output token.
* @dev This method is only callable by an exchanger.
* @param newPath The new router path.
*/
function updatePath(address[] memory newPath) onlyExchanger external {
require(newPath[0]==address(FeeExchanger._inputToken), "FE: PATH INPUT");
require(newPath[newPath.length-1]==address(FeeExchanger._outputToken), "FE: PATH OUTPUT");
_path = newPath;
}
/**
* @notice View function to return the router path.
* @return The router path.
*/
function getPath() external view returns (address[] memory) {
return _path;
}
}
| Initialises the Sushiswap Exchanger contract. Most of the initialisation is done as part of the `FeeExchanger` initialisation. This method sets the internal sushiswap router address. This method also initialises the router path. routerAddress The address of the sushiswap router. inputToken The token which the protocol fees are generated in. This should set to the WETH address. outputToken The token which this contract will exchange fees into. outputAddress The address where fees will be redirected to./ | function initialize(IUniswapV2Router02 routerAddress, IERC20Upgradeable inputToken, IERC20Upgradeable outputToken, address outputAddress) public initializer {
FeeExchanger.__FeeExchanger_init(inputToken, outputToken, outputAddress);
_sushiswapRouter = routerAddress;
_path = new address[](2);
_path[0] = address(inputToken);
_path[1] = address(outputToken);
}
| 7,302,026 |
./partial_match/1/0x56EAb4C7dC3bf7C31aa87d5Ed4Eb853A9872aBcf/sources/contracts/slopes/Slopes.sol | external function to claim all rewards | function claimAll()
external
override
{
_claimAll(msg.sender);
}
| 4,052,659 |
./full_match/1/0x63faF7BB2e6FC14619441cc9bA64c4EAf54A60ac/sources/contracts/PowerFarms/wstETHPowerFarm/wstETHFarm.sol | Internal function combining the core logic for {closingPosition()}. Note: {_minOutAmount} passed through UI by querring {get_dy()} from curve pool contract./ | function _closingPosition(
uint256 _nftId,
uint256 _minOutAmount,
bool _ethBack
)
internal
{
uint256 borrowShares = _getPositionBorrowShares(
_nftId
);
uint256 lendingShares = _getPositionLendingShares(
_nftId
);
uint256 borrowAmount = _getPositionBorrowToken(
_nftId
);
_executeBalancerFlashLoan(
{
_nftId: _nftId,
_amount: borrowAmount,
_initialAmount: 0,
_lendingShares: lendingShares,
_borrowShares: borrowShares,
_minAmountOut: _minOutAmount,
_ethBack: _ethBack
}
);
}
| 4,948,481 |
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.5.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;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.5.0;
/**
* @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);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* 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;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.5.5;
/**
* @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 Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @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].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.5.0;
/**
* @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 ERC20;` 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));
}
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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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/base/interface/IController.sol
pragma solidity 0.5.16;
interface IController {
event SharePriceChangeLog(
address indexed vault,
address indexed strategy,
uint256 oldSharePrice,
uint256 newSharePrice,
uint256 timestamp
);
// [Grey list]
// An EOA can safely interact with the system no matter what.
// If you're using Metamask, you're using an EOA.
// Only smart contracts may be affected by this grey list.
//
// This contract will not be able to ban any EOA from the system
// even if an EOA is being added to the greyList, he/she will still be able
// to interact with the whole system as if nothing happened.
// Only smart contracts will be affected by being added to the greyList.
// This grey list is only used in Vault.sol, see the code there for reference
function greyList(address _target) external view returns(bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function doHardWork(address _vault) external;
function hasVault(address _vault) external returns(bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(address _strategy, address _token, uint256 amount) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
function feeRewardForwarder() external view returns(address);
function setFeeRewardForwarder(address _value) external;
function addHardWorker(address _worker) external;
}
// File contracts/base/interface/IFeeRewardForwarderV6.sol
pragma solidity 0.5.16;
interface IFeeRewardForwarderV6 {
function poolNotifyFixedTarget(address _token, uint256 _amount) external;
function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external;
function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external;
function profitSharingPool() external view returns (address);
function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external;
}
// File contracts/base/inheritance/Storage.sol
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
// File contracts/base/inheritance/Governable.sol
pragma solidity 0.5.16;
contract Governable {
Storage public store;
constructor(address _store) public {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
modifier onlyGovernance() {
require(store.isGovernance(msg.sender), "Not governance");
_;
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
function governance() public view returns (address) {
return store.governance();
}
}
// File contracts/base/inheritance/Controllable.sol
pragma solidity 0.5.16;
contract Controllable is Governable {
constructor(address _storage) Governable(_storage) public {
}
modifier onlyController() {
require(store.isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance(){
require((store.isController(msg.sender) || store.isGovernance(msg.sender)),
"The caller must be controller or governance");
_;
}
function controller() public view returns (address) {
return store.controller();
}
}
// File contracts/base/inheritance/RewardTokenProfitNotifier.sol
pragma solidity 0.5.16;
contract RewardTokenProfitNotifier is Controllable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public profitSharingNumerator;
uint256 public profitSharingDenominator;
address public rewardToken;
constructor(
address _storage,
address _rewardToken
) public Controllable(_storage){
rewardToken = _rewardToken;
// persist in the state for immutability of the fee
profitSharingNumerator = 30; //IController(controller()).profitSharingNumerator();
profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator();
require(profitSharingNumerator < profitSharingDenominator, "invalid profit share");
}
event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);
event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);
function notifyProfitInRewardToken(uint256 _rewardBalance) internal {
if( _rewardBalance > 0 ){
uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator);
emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp);
IERC20(rewardToken).safeApprove(controller(), 0);
IERC20(rewardToken).safeApprove(controller(), feeAmount);
IController(controller()).notifyFee(
rewardToken,
feeAmount
);
} else {
emit ProfitLogInReward(0, 0, block.timestamp);
}
}
function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal {
if( _rewardBalance > 0 ){
uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator);
address forwarder = IController(controller()).feeRewardForwarder();
emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp);
IERC20(rewardToken).safeApprove(forwarder, 0);
IERC20(rewardToken).safeApprove(forwarder, _rewardBalance);
IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts(
rewardToken,
feeAmount,
pool,
_rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000)
);
} else {
emit ProfitAndBuybackLog(0, 0, block.timestamp);
}
}
}
// File contracts/base/interface/IStrategy.sol
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(address recipient, address token, uint256 amount) external;
function doHardWork() external;
function depositArbCheck() external view returns(bool);
}
// File contracts/base/interface/ILiquidator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.16;
interface ILiquidator {
event Swap(
address indexed buyToken,
address indexed sellToken,
address indexed target,
address initiator,
uint256 amountIn,
uint256 slippage,
uint256 total
);
function swapTokenOnMultipleDEXes(
uint256 amountIn,
uint256 amountOutMin,
address target,
bytes32[] calldata dexes,
address[] calldata path
) external;
function swapTokenOnDEX(
uint256 amountIn,
uint256 amountOutMin,
address target,
bytes32 dexName,
address[] calldata path
) external;
function getAllDexes() external view returns (bytes32[] memory);
}
// File contracts/base/interface/ILiquidatorRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.16;
interface ILiquidatorRegistry {
function universalLiquidator() external view returns(address);
function setUniversalLiquidator(address _ul) external;
function getPath(
bytes32 dex,
address inputToken,
address outputToken
) external view returns(address[] memory);
function setPath(
bytes32 dex,
address inputToken,
address outputToken,
address[] calldata path
) external;
}
// File contracts/base/StrategyBaseUL.sol
//SPDX-License-Identifier: Unlicense
pragma solidity 0.5.16;
contract StrategyBaseUL is IStrategy, RewardTokenProfitNotifier {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event ProfitsNotCollected(address);
event Liquidating(address, uint256);
address public underlying;
address public vault;
mapping (address => bool) public unsalvagableTokens;
address public universalLiquidatorRegistry;
modifier restricted() {
require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()),
"The sender has to be the controller or vault or governance");
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _rewardToken,
address _universalLiquidatorRegistry
) RewardTokenProfitNotifier(_storage, _rewardToken) public {
underlying = _underlying;
vault = _vault;
unsalvagableTokens[_rewardToken] = true;
unsalvagableTokens[_underlying] = true;
universalLiquidatorRegistry = _universalLiquidatorRegistry;
}
function universalLiquidator() public view returns(address) {
return ILiquidatorRegistry(universalLiquidatorRegistry).universalLiquidator();
}
}
// File contracts/base/interface/IVault.sol
pragma solidity 0.5.16;
interface IVault {
function initializeVault(
address _storage,
address _underlying,
uint256 _toInvestNumerator,
uint256 _toInvestDenominator
) external ;
function balanceOf(address) external view returns (uint256);
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
// function store() external view returns (address);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function announceStrategyUpdate(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256);
// hard work should be callable only by the controller (by the hard worker) or by governance
function doHardWork() external;
}
// File contracts/base/interface/IRewardDistributionSwitcher.sol
pragma solidity 0.5.16;
contract IRewardDistributionSwitcher {
function switchingAllowed(address) external returns(bool);
function returnOwnership(address poolAddr) external;
function enableSwitchers(address[] calldata switchers) external;
function setSwithcer(address switcher, bool allowed) external;
function setPoolRewardDistribution(address poolAddr, address newRewardDistributor) external;
}
// File contracts/base/interface/INoMintRewardPool.sol
pragma solidity 0.5.16;
interface INoMintRewardPool {
function withdraw(uint) external;
function getReward() external;
function stake(uint) external;
function balanceOf(address) external view returns (uint256);
function earned(address account) external view returns (uint256);
function exit() external;
function rewardDistribution() external view returns (address);
function lpToken() external view returns(address);
function rewardToken() external view returns(address);
// only owner
function setRewardDistribution(address _rewardDistributor) external;
function transferOwnership(address _owner) external;
function notifyRewardAmount(uint256 _reward) external;
}
// File contracts/strategies/basis/interfaces/IBASPool.sol
pragma solidity 0.5.16;
interface IBASPool {
/* ================= CALLS ================= */
function tokenOf(uint256 _pid) external view returns (address);
function poolIdsOf(address _token) external view returns (uint256[] memory);
function totalSupply(uint256 _pid) external view returns (uint256);
function balanceOf(uint256 _pid, address _owner)
external
view
returns (uint256);
function rewardRatePerPool(uint256 _pid) external view returns (uint256);
function rewardPerToken(uint256 _pid) external view returns (uint256);
function rewardEarned(uint256 _pid, address _target)
external
view
returns (uint256);
/* ================= TXNS ================= */
function update(uint256 _pid) external;
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function claimReward(uint256 _pid) external;
function exit(uint256 _pid) external;
}
// File contracts/strategies/basis/Basis2FarmStrategyV3.sol
pragma solidity 0.5.16;
/*
* This is a general strategy for yields that are based on the synthetix reward contract
* for example, yam, spaghetti, ham, shrimp.
*
* One strategy is deployed for one underlying asset, but the design of the contract
* should allow it to switch between different reward contracts.
*
* It is important to note that not all SNX reward contracts that are accessible via the same interface are
* suitable for this Strategy. One concrete example is CREAM.finance, as it implements a "Lock" feature and
* would not allow the user to withdraw within some timeframe after the user have deposited.
* This would be problematic to user as our "invest" function in the vault could be invoked by anyone anytime
* and thus locking/reverting on subsequent withdrawals. Another variation is the YFI Governance: it can
* activate a vote lock to stop withdrawal.
*
* Ref:
* 1. CREAM https://etherscan.io/address/0xc29e89845fa794aa0a0b8823de23b760c3d766f5#code
* 2. YAM https://etherscan.io/address/0x8538E5910c6F80419CD3170c26073Ff238048c9E#code
* 3. SHRIMP https://etherscan.io/address/0x9f83883FD3cadB7d2A83a1De51F9Bf483438122e#code
* 4. BASED https://etherscan.io/address/0x5BB622ba7b2F09BF23F1a9b509cd210A818c53d7#code
* 5. YFII https://etherscan.io/address/0xb81D3cB2708530ea990a287142b82D058725C092#code
* 6. YFIGovernance https://etherscan.io/address/0xBa37B002AbaFDd8E89a1995dA52740bbC013D992#code
*
*
*
* Respecting the current system design of choosing the best strategy under the vault, and also rewarding/funding
* the public key that invokes the switch of strategies, this smart contract should be deployed twice and linked
* to the same vault. When the governance want to rotate the crop, they would set the reward source on the strategy
* that is not active, then set that apy higher and this one lower.
*
* Consequently, in the smart contract we restrict that we can only set a new reward source when it is not active.
*
*/
contract Basis2FarmStrategyV3 is StrategyBaseUL {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public farm;
address public distributionPool;
address public distributionSwitcher;
address public rewardToken;
bool public pausedInvesting = false; // When this flag is true, the strategy will not be able to invest. But users should be able to withdraw.
IBASPool public rewardPool;
// a flag for disabling selling for simplified emergency exit
bool public sell = true;
uint256 public sellFloor = 1e6;
// Instead of trying to pass in the detailed liquidation path and different dexes to the liquidator,
// we just pass in the input output of the liquidation path:
// [ MIC, WETH, FARM ] , [SUSHI, UNI]
//
// This means that:
// the first dex is sushi, the input is MIC and output is WETH.
// the second dex is uni, the input is WETH and the output is FARM.
// the universal liquidator itself would record the best path to liquidate from MIC to WETH on Sushiswap
// provides the path for liquidating a token
address [] public liquidationPath;
// specifies which DEX is the token liquidated on
bytes32 [] public liquidationDexes;
// if the flag is set, then it would read the previous reward distribution from the pool
// otherwise, it would read from `setRewardDistributionTo` and ask the distributionSwitcher to set to it.
bool public autoRevertRewardDistribution;
address public defaultRewardDistribution;
uint poolId;
event ProfitsNotCollected();
// This is only used in `investAllUnderlying()`
// The user can still freely withdraw from the strategy
modifier onlyNotPausedInvesting() {
require(!pausedInvesting, "Action blocked as the strategy is in emergency state");
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _rewardPool,
uint _rewardPoolId,
address _rewardToken,
address _universalLiquidatorRegistry,
address _farm,
address _distributionPool,
address _distributionSwitcher
)
StrategyBaseUL(_storage, _underlying, _vault, _farm, _universalLiquidatorRegistry)
public {
require(_vault == INoMintRewardPool(_distributionPool).lpToken(), "distribution pool's lp must be the vault");
require(_farm == INoMintRewardPool(_distributionPool).rewardToken(), "distribution pool's reward must be FARM");
farm = _farm;
distributionPool = _distributionPool;
rewardToken = _rewardToken;
distributionSwitcher = _distributionSwitcher;
rewardPool = IBASPool(_rewardPool);
poolId = _rewardPoolId;
}
function depositArbCheck() public view returns(bool) {
return true;
}
/*
* In case there are some issues discovered about the pool or underlying asset
* Governance can exit the pool properly
* The function is only used for emergency to exit the pool
*/
function emergencyExit() public onlyGovernance {
if (rewardPool.balanceOf(poolId, address(this)) > 0) {
rewardPool.withdraw(poolId, rewardPool.balanceOf(poolId, address(this)));
}
pausedInvesting = true;
}
/*
* Resumes the ability to invest into the underlying reward pools
*/
function continueInvesting() public onlyGovernance {
pausedInvesting = false;
}
function setLiquidationPaths(address [] memory _liquidationPath, bytes32[] memory _dexes) public onlyGovernance {
liquidationPath = _liquidationPath;
liquidationDexes = _dexes;
}
function _liquidateReward() internal {
uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this));
if (!sell || rewardBalance < sellFloor) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected();
return;
}
// sell reward token to FARM
// we can accept 1 as minimum because this is called only by a trusted role
address uliquidator = universalLiquidator();
IERC20(rewardToken).safeApprove(uliquidator, 0);
IERC20(rewardToken).safeApprove(uliquidator, rewardBalance);
ILiquidator(uliquidator).swapTokenOnMultipleDEXes(
rewardBalance,
1,
address(this), // target
liquidationDexes,
liquidationPath
);
uint256 farmAmount = IERC20(farm).balanceOf(address(this));
// Use farm as profit sharing base, sending it
notifyProfitInRewardToken(farmAmount);
// The remaining farms should be distributed to the distribution pool
farmAmount = IERC20(farm).balanceOf(address(this));
// Switch reward distribution temporarily, notify reward, switch it back
address prevRewardDistribution;
if(autoRevertRewardDistribution) {
prevRewardDistribution = INoMintRewardPool(distributionPool).rewardDistribution();
} else {
prevRewardDistribution = defaultRewardDistribution;
}
IRewardDistributionSwitcher(distributionSwitcher).setPoolRewardDistribution(distributionPool, address(this));
// transfer and notify with the remaining farm amount
IERC20(farm).safeTransfer(distributionPool, farmAmount);
INoMintRewardPool(distributionPool).notifyRewardAmount(farmAmount);
IRewardDistributionSwitcher(distributionSwitcher).setPoolRewardDistribution(distributionPool, prevRewardDistribution);
}
/*
* Stakes everything the strategy holds into the reward pool
*/
function investAllUnderlying() internal onlyNotPausedInvesting {
// this check is needed, because most of the SNX reward pools will revert if
// you try to stake(0).
if(IERC20(underlying).balanceOf(address(this)) > 0) {
IERC20(underlying).approve(address(rewardPool), IERC20(underlying).balanceOf(address(this)));
rewardPool.deposit(poolId, IERC20(underlying).balanceOf(address(this)));
}
}
/*
* Withdraws all the asset to the vault
*/
function withdrawAllToVault() public restricted {
if (rewardPool.balanceOf(poolId, address(this)) > 0) {
rewardPool.exit(poolId);
}
_liquidateReward();
if (IERC20(underlying).balanceOf(address(this)) > 0) {
IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this)));
}
}
/*
* Withdraws all the asset to the vault
*/
function withdrawToVault(uint256 amount) public restricted {
// Typically there wouldn't be any amount here
// however, it is possible because of the emergencyExit
if(amount > IERC20(underlying).balanceOf(address(this))){
// While we have the check above, we still using SafeMath below
// for the peace of mind (in case something gets changed in between)
uint256 needToWithdraw = amount.sub(IERC20(underlying).balanceOf(address(this)));
rewardPool.withdraw(poolId, Math.min(rewardPool.balanceOf(poolId, address(this)), needToWithdraw));
}
IERC20(underlying).safeTransfer(vault, amount);
}
/*
* Note that we currently do not have a mechanism here to include the
* amount of reward that is accrued.
*/
function investedUnderlyingBalance() external view returns (uint256) {
// Adding the amount locked in the reward pool and the amount that is somehow in this contract
// both are in the units of "underlying"
// The second part is needed because there is the emergency exit mechanism
// which would break the assumption that all the funds are always inside of the reward pool
return rewardPool.balanceOf(poolId, address(this)).add(IERC20(underlying).balanceOf(address(this)));
}
/*
* Governance or Controller can claim coins that are somehow transferred into the contract
* Note that they cannot come in take away coins that are used and defined in the strategy itself
* Those are protected by the "unsalvagableTokens". To check, see where those are being flagged.
*/
function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvagable");
IERC20(token).safeTransfer(recipient, amount);
}
/*
* Get the reward, sell it in exchange for underlying, invest what you got.
* It's not much, but it's honest work.
*
* Note that although `onlyNotPausedInvesting` is not added here,
* calling `investAllUnderlying()` affectively blocks the usage of `doHardWork`
* when the investing is being paused by governance.
*/
function doHardWork() external onlyNotPausedInvesting restricted {
rewardPool.claimReward(poolId);
_liquidateReward();
investAllUnderlying();
}
/**
* Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the
* simplest possible way.
*/
function setSell(bool s) public onlyGovernance {
sell = s;
}
/**
* Sets the minimum amount of CRV needed to trigger a sale.
*/
function setSellFloor(uint256 floor) public onlyGovernance {
sellFloor = floor;
}
function setRewardPool(address _rewardPool, uint256 _pid) public onlyGovernance {
require(IBASPool(_rewardPool).tokenOf(_pid) == underlying, "Pool underlying missmatch");
if (rewardPool.balanceOf(poolId, address(this)) > 0) {
rewardPool.exit(poolId);
}
_liquidateReward();
poolId = _pid;
rewardPool = IBASPool(_rewardPool);
investAllUnderlying();
}
}
// File contracts/strategies/basis/Basis2FarmStrategyMainnet_DAI_BASV3.sol
pragma solidity 0.5.16;
contract Basis2FarmStrategyMainnet_DAI_BASV3 is Basis2FarmStrategyV3 {
address public constant __dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public __basv2 = address(0x106538CC16F938776c7c180186975BCA23875287);
address public __dai_basv2 = address(0x3E78F2E7daDe07ea685F8612F00477FD97162F1e);
address public constant __rewardPool = address(0x818F83333244bA4BB72Dab0b60b1901158402f2E);
address public constant __universalLiquidatorRegistry = address(0x7882172921E99d590E097cD600554339fBDBc480);
address public constant __farm = address(0xa0246c9032bC3A600820415aE600c6388619A14D);
address public constant __weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public constant __notifyHelper = address(0xE20c31e3d08027F5AfACe84A3A46B7b3B165053c);
constructor(
address _storage,
address _vault,
address _distributionPool,
address _distributionSwitcher
)
Basis2FarmStrategyV3(
_storage,
__dai_basv2,
_vault,
__rewardPool,
2, // pool ID
__basv2,
__universalLiquidatorRegistry,
__farm,
_distributionPool,
_distributionSwitcher
)
public {
require(IVault(_vault).underlying() == __dai_basv2, "Underlying mismatch");
liquidationPath = [__basv2, farm];
liquidationDexes.push(bytes32(uint256(keccak256("uni"))));
defaultRewardDistribution = __notifyHelper;
}
} | Get the reward, sell it in exchange for underlying, invest what you got. It's not much, but it's honest work. Note that although `onlyNotPausedInvesting` is not added here, calling `investAllUnderlying()` affectively blocks the usage of `doHardWork` when the investing is being paused by governance./ | function doHardWork() external onlyNotPausedInvesting restricted {
rewardPool.claimReward(poolId);
_liquidateReward();
investAllUnderlying();
}
| 169,438 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IMillionPieces.sol";
import "./interfaces/IAuction.sol";
import "./helpers/ProxyRegistry.sol";
/**
* @title Auction
*/
contract Auction is IAuction, Ownable {
using SafeMath for uint256;
uint256 public constant BATCH_PURCHASE_LIMIT = 25;
uint256 public constant PRICE_FOR_SEGMENT = 0.1 ether;
address payable public fund;
address public immutable proxyRegistryAddress;
IMillionPieces public immutable millionPieces;
event NewPurchase(address purchaser, address receiver, uint256 tokenId, uint256 weiAmount);
constructor(
address _millionPieces,
address payable _fund,
address _proxyRegistryAddress
) public {
fund = _fund;
proxyRegistryAddress = _proxyRegistryAddress;
millionPieces = IMillionPieces(_millionPieces);
}
fallback () external payable { revert(); }
receive () external payable { revert(); }
// --------------------
// PUBLIC
// --------------------
function buySingle(address receiver, uint256 tokenId) external payable override {
require(msg.value >= PRICE_FOR_SEGMENT, "buySingle: Not enough ETH for purchase!");
_buySingle(receiver, tokenId);
}
function buyMany(
address[] calldata receivers,
uint256[] calldata tokenIds
) external payable override {
uint256 tokensCount = tokenIds.length;
require(tokensCount > 0 && tokensCount <= BATCH_PURCHASE_LIMIT, "buyMany: Arrays should bigger 0 and less then max limit!");
require(tokensCount == receivers.length, "buyMany: Arrays should be equal to each other!");
require(msg.value >= tokensCount.mul(PRICE_FOR_SEGMENT), "buyMany: Not enough ETH for purchase!");
_buyMany(receivers, tokenIds);
}
function mint(uint256 tokenId, address receiver) public {
// Must be sent from the owner proxy or owner.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
require(address(proxyRegistry.proxies(owner())) == msg.sender || owner() == msg.sender, "mint: Not auth!");
_buySingle(receiver, tokenId);
}
function changeFundAddress(address payable newFund) external onlyOwner {
require(newFund != address(0), "changeFundAddress: Empty fund address!");
fund = newFund;
}
// --------------------
// INTERNAL
// -------------------
function _buySingle(address receiver, uint256 tokenId) private {
// Mint token to receiver
_mintNft(receiver, tokenId);
// Emit single segment purchase event
emit NewPurchase(msg.sender, receiver, tokenId, msg.value);
// Send ETH to fund address
_transferEth(fund, msg.value);
}
function _buyMany(address[] memory receivers, uint256[] memory tokenIds) private {
uint256 tokensCount = tokenIds.length;
uint256 actualPurchasedSegments = 0;
uint256 ethPerEachSegment = msg.value.div(tokensCount);
for (uint256 i = 0; i < tokensCount; i++) {
// Transfer if tokens not exist, else sent ETH back to purchaser
if (_isPurchasable(tokenIds[i])) {
// Mint token to receiver
_mintNft(receivers[i], tokenIds[i]);
actualPurchasedSegments++;
emit NewPurchase(msg.sender, receivers[i], tokenIds[i], ethPerEachSegment);
}
}
// Send ETH to fund address
_transferEth(fund, actualPurchasedSegments.mul(ethPerEachSegment));
// Send non-purchased funds to sender address back
if (tokensCount != actualPurchasedSegments) {
_transferEth(msg.sender, (tokensCount.sub(actualPurchasedSegments)).mul(ethPerEachSegment));
}
}
/**
* @notice Transfer amount of ETH to the fund address.
*/
function _transferEth(address receiver, uint256 amount) private {
(bool success, ) = receiver.call{value: amount}("");
require(success, "_transferEth: Failed to transfer funds!");
}
/**
* @notice Mint simple segment.
*/
function _mintNft(address receiver, uint256 tokenId) private {
millionPieces.mintTo(receiver, tokenId);
}
/**
* @notice Is provided token exists or not.
*/
function _isPurchasable(uint256 tokenId) private view returns (bool) {
return !millionPieces.exists(tokenId);
}
}
// 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
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;
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.12;
/**
* @title IMillionPieces
*/
interface IMillionPieces {
function mintTo(address to, uint256 tokenId) external;
function mintToSpecial(address to, uint256 tokenId) external;
function createArtwork(string calldata name) external;
function setTokenURI(uint256 tokenId, string calldata uri) external;
function setBaseURI(string calldata baseURI) external;
function exists(uint256 tokenId) external view returns (bool);
function isSpecialSegment(uint256 tokenId) external pure returns (bool);
function isValidArtworkSegment(uint256 tokenId) external view returns (bool);
function getArtworkName(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.12;
/**
* @title IAuction
*/
interface IAuction {
function buySingle(address receiver, uint256 tokenId) external payable;
function buyMany(address[] calldata receivers, uint256[] calldata tokenIds) external payable;
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// 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;
}
}
| IMillionPieces/ | interface IMillionPieces {
function mintTo(address to, uint256 tokenId) external;
function mintToSpecial(address to, uint256 tokenId) external;
function createArtwork(string calldata name) external;
function setTokenURI(uint256 tokenId, string calldata uri) external;
function setBaseURI(string calldata baseURI) external;
function exists(uint256 tokenId) external view returns (bool);
function isSpecialSegment(uint256 tokenId) external pure returns (bool);
function isValidArtworkSegment(uint256 tokenId) external view returns (bool);
function getArtworkName(uint256 id) external view returns (string memory);
}
| 1,649,384 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title IERC1155 Non-Fungible Token Creator basic interface
*/
interface IERC1155TokenCreator {
/**
* @dev Gets the creator of the token
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function tokenCreator(uint256 _tokenId)
external
view
returns (address payable);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title IMarketplaceSettings Settings governing a marketplace.
*/
interface IMarketplaceSettings {
/////////////////////////////////////////////////////////////////////////
// Marketplace Min and Max Values
/////////////////////////////////////////////////////////////////////////
/**
* @dev Get the max value to be used with the marketplace.
* @return uint256 wei value.
*/
function getMarketplaceMaxValue() external view returns (uint256);
/**
* @dev Get the max value to be used with the marketplace.
* @return uint256 wei value.
*/
function getMarketplaceMinValue() external view returns (uint256);
/////////////////////////////////////////////////////////////////////////
// Marketplace Fee
/////////////////////////////////////////////////////////////////////////
/**
* @dev Get the marketplace fee percentage.
* @return uint8 wei fee.
*/
function getMarketplaceFeePercentage() external view returns (uint8);
/**
* @dev Utility function for calculating the marketplace fee for given amount of wei.
* @param _amount uint256 wei amount.
* @return uint256 wei fee.
*/
function calculateMarketplaceFee(uint256 _amount)
external
view
returns (uint256);
/////////////////////////////////////////////////////////////////////////
// Primary Sale Fee
/////////////////////////////////////////////////////////////////////////
/**
* @dev Get the primary sale fee percentage for a specific ERC1155 contract.
* @return uint8 wei primary sale fee.
*/
function getERC1155ContractPrimarySaleFeePercentage()
external
view
returns (uint8);
/**
* @dev Utility function for calculating the primary sale fee for given amount of wei
* @param _amount uint256 wei amount.
* @return uint256 wei fee.
*/
function calculatePrimarySaleFee(uint256 _amount)
external
view
returns (uint256);
/**
* @dev Check whether the ERC1155 token has sold at least once.
* @param _tokenId uint256 token ID.
* @return bool of whether the token has sold.
*/
function hasTokenSold(uint256 _tokenId)
external
view
returns (bool);
/**
* @dev Mark a token as sold.
* Requirements:
*
* - `_contractAddress` cannot be the zero address.
* @param _tokenId uint256 token ID.
* @param _hasSold bool of whether the token should be marked sold or not.
*/
function markERC1155Token(
uint256 _tokenId,
bool _hasSold
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Interface for interacting with the Nifter contract that holds Nifter beta tokens.
*/
interface INifter {
/**
* @dev Gets the creator of the token
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function creatorOfToken(uint256 _tokenId)
external
view
returns (address payable);
/**
* @dev Gets the Service Fee
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function getServiceFee(uint256 _tokenId)
external
view
returns (uint8);
/**
* @dev Gets the price type
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
* @return get the price type
*/
function getPriceType(uint256 _tokenId, address _owner)
external
view
returns (uint8);
/**
* @dev update price only from auction.
* @param _price price of the token
* @param _tokenId uint256 id of the token.
* @param _owner address of the token owner
*/
function setPrice(uint256 _price, uint256 _tokenId, address _owner) external;
/**
* @dev update bids only from auction.
* @param _bid bid Amount
* @param _bidder bidder address
* @param _tokenId uint256 id of the token.
* @param _owner address of the token owner
*/
function setBid(uint256 _bid, address _bidder, uint256 _tokenId, address _owner) external;
/**
* @dev remove token from sale
* @param _tokenId uint256 id of the token.
* @param _owner owner of the token
*/
function removeFromSale(uint256 _tokenId, address _owner) external;
/**
* @dev get tokenIds length
*/
function getTokenIdsLength() external view returns (uint256);
/**
* @dev get token Id
* @param _index uint256 index
*/
function getTokenId(uint256 _index) external view returns (uint256);
/**
* @dev Gets the owners
* @param _tokenId uint256 ID of the token
*/
function getOwners(uint256 _tokenId)
external
view
returns (address[] memory owners);
/**
* @dev Gets the is for sale
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function getIsForSale(uint256 _tokenId, address _owner) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface INifterMarketAuction {
/**
* @dev Set the token for sale. The owner of the token must be the sender and have the marketplace approved.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei value that the item is for sale
*/
function setSalePrice(
uint256 _tokenId,
uint256 _amount,
address _owner
) external;
/**
* @dev set
* @param _bidAmount uint256 value in wei to bid.
* @param _startTime end time of bid
* @param _endTime end time of bid
* @param _owner address of the token owner
* @param _tokenId uint256 ID of the token
*/
function setInitialBidPriceWithRange(
uint256 _bidAmount,
uint256 _startTime,
uint256 _endTime,
address _owner,
uint256 _tokenId
) external;
/**
* @dev has active bid
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function hasTokenActiveBid(uint256 _tokenId, address _owner) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IERC1155TokenCreator.sol";
/**
* @title IERC1155CreatorRoyalty Token level royalty interface.
*/
interface INifterRoyaltyRegistry is IERC1155TokenCreator {
/**
* @dev Get the royalty fee percentage for a specific ERC1155 contract.
* @param _tokenId uint256 token ID.
* @return uint8 wei royalty fee.
*/
function getTokenRoyaltyPercentage(
uint256 _tokenId
) external view returns (uint8);
/**
* @dev Utililty function to calculate the royalty fee for a token.
* @param _tokenId uint256 token ID.
* @param _amount uint256 wei amount.
* @return uint256 wei fee.
*/
function calculateRoyaltyFee(
uint256 _tokenId,
uint256 _amount
) external view returns (uint256);
/**
* @dev Sets the royalty percentage set for an Nifter token
* Requirements:
* - `_percentage` must be <= 100.
* - only the owner of this contract or the creator can call this method.
* @param _tokenId uint256 token ID.
* @param _percentage uint8 wei royalty fee.
*/
function setPercentageForTokenRoyalty(
uint256 _tokenId,
uint8 _percentage
) external returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ISendValueProxy {
function sendValue(address payable _to) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./SendValueProxy.sol";
/**
* @dev Contract with a ISendValueProxy that will catch reverts when attempting to transfer funds.
*/
contract MaybeSendValue {
SendValueProxy proxy;
constructor() internal {
proxy = new SendValueProxy();
}
/**
* @dev Maybe send some wei to the address via a proxy. Returns true on success and false if transfer fails.
* @param _to address to send some value to.
* @param _value uint256 amount to send.
*/
function maybeSendValue(address payable _to, uint256 _value)
internal
returns (bool)
{
_to.transfer(_value);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./INifterMarketAuction.sol";
import "./INifterRoyaltyRegistry.sol";
import "./IMarketplaceSettings.sol";
import "./Payments.sol";
import "./INifter.sol";
contract NifterMarketAuction is INifterMarketAuction, Ownable, Payments {
using SafeMath for uint256;
/////////////////////////////////////////////////////////////////////////
// Structs
/////////////////////////////////////////////////////////////////////////
// The active bid for a given token, contains the bidder, the marketplace fee at the time of the bid, and the amount of wei placed on the token
struct ActiveBid {
address payable bidder;
uint8 marketplaceFee;
uint256 amount;
}
struct ActiveBidRange {
uint256 startTime;
uint256 endTime;
}
// The sale price for a given token containing the seller and the amount of wei to be sold for
struct SalePrice {
address payable seller;
uint256 amount;
}
/////////////////////////////////////////////////////////////////////////
// State Variables
/////////////////////////////////////////////////////////////////////////
// Marketplace Settings Interface
IMarketplaceSettings public iMarketplaceSettings;
// Creator Royalty Interface
INifterRoyaltyRegistry public iERC1155CreatorRoyalty;
// Nifter contract
INifter public nifter;
//erc1155 contract
IERC1155 public erc1155;
// Mapping from ERC1155 contract to mapping of tokenId to sale price.
mapping(uint256 => mapping(address => SalePrice)) private salePrice;
// Mapping of ERC1155 contract to mapping of token ID to the current bid amount.
mapping(uint256 => mapping(address => ActiveBid)) private activeBid;
mapping(uint256 => mapping(address => ActiveBidRange)) private activeBidRange;
mapping(address => uint256) public bidBalance;
// A minimum increase in bid amount when out bidding someone.
uint8 public minimumBidIncreasePercentage; // 10 = 10%
/////////////////////////////////////////////////////////////////////////////
// Events
/////////////////////////////////////////////////////////////////////////////
event Sold(
address indexed _buyer,
address indexed _seller,
uint256 _amount,
uint256 _tokenId
);
event SetSalePrice(
uint256 _amount,
uint256 _tokenId
);
event Bid(
address indexed _bidder,
uint256 _amount,
uint256 _tokenId
);
event SetInitialBidPriceWithRange(
uint256 _bidAmount,
uint256 _startTime,
uint256 _endTime,
address _owner,
uint256 _tokenId
);
event AcceptBid(
address indexed _bidder,
address indexed _seller,
uint256 _amount,
uint256 _tokenId
);
event CancelBid(
address indexed _bidder,
uint256 _amount,
uint256 _tokenId
);
/////////////////////////////////////////////////////////////////////////
// Constructor
/////////////////////////////////////////////////////////////////////////
/**
* @dev Initializes the contract setting the market settings and creator royalty interfaces.
* @param _iMarketSettings address to set as iMarketplaceSettings.
* @param _iERC1155CreatorRoyalty address to set as iERC1155CreatorRoyalty.
* @param _nifter address of the nifter contract
*/
constructor(address _iMarketSettings, address _iERC1155CreatorRoyalty, address _nifter)
public
{
require(
_iMarketSettings != address(0),
"constructor::Cannot have null address for _iMarketSettings"
);
require(
_iERC1155CreatorRoyalty != address(0),
"constructor::Cannot have null address for _iERC1155CreatorRoyalty"
);
require(
_nifter != address(0),
"constructor::Cannot have null address for _nifter"
);
// Set iMarketSettings
iMarketplaceSettings = IMarketplaceSettings(_iMarketSettings);
// Set iERC1155CreatorRoyalty
iERC1155CreatorRoyalty = INifterRoyaltyRegistry(_iERC1155CreatorRoyalty);
nifter = INifter(_nifter);
erc1155 = IERC1155(_nifter);
minimumBidIncreasePercentage = 10;
}
/////////////////////////////////////////////////////////////////////////
// Get owner of the token
/////////////////////////////////////////////////////////////////////////
/**
* @dev get owner of the token
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function isOwnerOfTheToken(uint256 _tokenId, address _owner) public view returns (bool) {
uint256 balance = erc1155.balanceOf(_owner, _tokenId);
return balance > 0;
}
/////////////////////////////////////////////////////////////////////////
// Get token sale price against token id
/////////////////////////////////////////////////////////////////////////
/**
* @dev get the token sale price against token id
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function getSalePrice(uint256 _tokenId, address _owner) external view returns (address payable, uint256){
SalePrice memory sp = salePrice[_tokenId][_owner];
return (sp.seller, sp.amount);
}
/////////////////////////////////////////////////////////////////////////
// get active bid against tokenId
/////////////////////////////////////////////////////////////////////////
/**
* @dev get active bid against token Id
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function getActiveBid(uint256 _tokenId, address _owner) external view returns (address payable, uint8, uint256){
ActiveBid memory ab = activeBid[_tokenId][_owner];
return (ab.bidder, ab.marketplaceFee, ab.amount);
}
/////////////////////////////////////////////////////////////////////////
// has active bid
/////////////////////////////////////////////////////////////////////////
/**
* @dev has active bid
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function hasTokenActiveBid(uint256 _tokenId, address _owner) external view override returns (bool){
ActiveBid memory ab = activeBid[_tokenId][_owner];
if (ab.bidder == _owner || ab.bidder == address(0))
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////
// get bid balance of user
/////////////////////////////////////////////////////////////////////////
/**
* @dev get bid balance of user
* @param _user address of the user
*/
function getBidBalance(address _user) external view returns (uint256){
return bidBalance[_user];
}
/////////////////////////////////////////////////////////////////////////
// get active bid range against token id
/////////////////////////////////////////////////////////////////////////
/**
* @dev get active bid range against token id
* @param _tokenId uint256 ID of the token
*/
function getActiveBidRange(uint256 _tokenId, address _owner) external view returns (uint256, uint256){
ActiveBidRange memory abr = activeBidRange[_tokenId][_owner];
return (abr.startTime, abr.endTime);
}
/////////////////////////////////////////////////////////////////////////
// withdrawMarketFunds
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to withdraw market funds
* Rules:
* - only owner
*/
function withdrawMarketFunds() external onlyOwner {
uint256 balance = address(this).balance;
_makePayable(owner()).transfer(balance);
}
/////////////////////////////////////////////////////////////////////////
// setIMarketplaceSettings
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the marketplace settings.
* Rules:
* - only owner
* - _address != address(0)
* @param _address address of the IMarketplaceSettings.
*/
function setMarketplaceSettings(address _address) public onlyOwner {
require(
_address != address(0),
"setMarketplaceSettings::Cannot have null address for _iMarketSettings"
);
iMarketplaceSettings = IMarketplaceSettings(_address);
}
/////////////////////////////////////////////////////////////////////////
// seNifter
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the marketplace settings.
* Rules:
* - only owner
* - _address != address(0)
* @param _address address of the IMarketplaceSettings.
*/
function setNifter(address _address) public onlyOwner {
require(
_address != address(0),
"setNifter::Cannot have null address for _INifter"
);
nifter = INifter(_address);
erc1155 = IERC1155(_address);
}
/////////////////////////////////////////////////////////////////////////
// setIERC1155CreatorRoyalty
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the IERC1155CreatorRoyalty.
* Rules:
* - only owner
* - _address != address(0)
* @param _address address of the IERC1155CreatorRoyalty.
*/
function setIERC1155CreatorRoyalty(address _address) public onlyOwner {
require(
_address != address(0),
"setIERC1155CreatorRoyalty::Cannot have null address for _iERC1155CreatorRoyalty"
);
iERC1155CreatorRoyalty = INifterRoyaltyRegistry(_address);
}
/////////////////////////////////////////////////////////////////////////
// setMinimumBidIncreasePercentage
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the minimum bid increase percentage.
* Rules:
* - only owner
* @param _percentage uint8 to set as the new percentage.
*/
function setMinimumBidIncreasePercentage(uint8 _percentage)
public
onlyOwner
{
minimumBidIncreasePercentage = _percentage;
}
/////////////////////////////////////////////////////////////////////////
// Modifiers (as functions)
/////////////////////////////////////////////////////////////////////////
/**
* @dev Checks that the token owner is approved for the ERC1155Market
* @param _owner address of the token owner
*/
function ownerMustHaveMarketplaceApproved(
address _owner
) internal view {
require(
erc1155.isApprovedForAll(_owner, address(this)),
"owner must have approved contract"
);
}
/**
* @dev Checks that the token is owned by the sender
* @param _tokenId uint256 ID of the token
*/
function senderMustBeTokenOwner(uint256 _tokenId)
internal
view
{
bool isOwner = isOwnerOfTheToken(_tokenId, msg.sender);
require(isOwner || msg.sender == address(nifter), 'sender must be the token owner');
}
/////////////////////////////////////////////////////////////////////////
// setSalePrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Set the token for sale. The owner of the token must be the sender and have the marketplace approved.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei value that the item is for sale
* @param _owner address of the token owner
*/
function setSalePrice(
uint256 _tokenId,
uint256 _amount,
address _owner
) external override {
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// The sender must be the token owner
senderMustBeTokenOwner(_tokenId);
if (_amount == 0) {
// Set not for sale and exit
_resetTokenPrice(_tokenId, _owner);
emit SetSalePrice(_amount, _tokenId);
return;
}
salePrice[_tokenId][_owner] = SalePrice(payable(_owner), _amount);
nifter.setPrice(_amount, _tokenId, _owner);
// nifter.putOnSale(0, _tokenId, _owner);
// nifter.setPriceType(0, _tokenId);
// nifter.setIsForSale(true, _tokenId, _owner);
emit SetSalePrice(_amount, _tokenId);
}
/**
* @dev restore data from old contract, only call by owner
* @param _oldAddress address of old contract.
* @param _oldNifterAddress get the token ids from the old nifter contract.
* @param _startIndex start index of array
* @param _endIndex end index of array
*/
function restore(address _oldAddress, address _oldNifterAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner {
NifterMarketAuction oldContract = NifterMarketAuction(_oldAddress);
INifter oldNifterContract = INifter(_oldNifterAddress);
uint256 length = oldNifterContract.getTokenIdsLength();
require(_startIndex < length, "wrong start index");
require(_endIndex <= length, "wrong end index");
for (uint i = _startIndex; i < _endIndex; i++) {
uint256 tokenId = oldNifterContract.getTokenId(i);
address[] memory owners = oldNifterContract.getOwners(tokenId);
for (uint j = 0; j < owners.length; j++) {
address owner = owners[j];
(address payable sender, uint256 amount) = oldContract.getSalePrice(tokenId, owner);
salePrice[tokenId][owner] = SalePrice(sender, amount);
(address payable bidder, uint8 marketplaceFee, uint256 bidAmount) = oldContract.getActiveBid(tokenId, owner);
activeBid[tokenId][owner] = ActiveBid(bidder, marketplaceFee, bidAmount);
uint256 serviceFee = bidAmount.mul(marketplaceFee).div(100);
bidBalance[bidder] = bidBalance[bidder].add(bidAmount.add(serviceFee));
(uint256 startTime, uint256 endTime) = oldContract.getActiveBidRange(tokenId, owner);
activeBidRange[tokenId][owner] = ActiveBidRange(startTime, endTime);
}
}
setMinimumBidIncreasePercentage(oldContract.minimumBidIncreasePercentage());
}
/////////////////////////////////////////////////////////////////////////
// safeBuy
/////////////////////////////////////////////////////////////////////////
/**
* @dev Purchase the token with the expected amount. The current token owner must have the marketplace approved.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei amount expecting to purchase the token for.
* @param _owner address of the token owner
*/
function safeBuy(
uint256 _tokenId,
uint256 _amount,
address _owner
) external payable {
// Make sure the tokenPrice is the expected amount
require(
salePrice[_tokenId][_owner].amount == _amount,
"safeBuy::Purchase amount must equal expected amount"
);
buy(_tokenId, _owner);
}
/////////////////////////////////////////////////////////////////////////
// buy
/////////////////////////////////////////////////////////////////////////
/**
* @dev Purchases the token if it is for sale.
* @param _tokenId uint256 ID of the token.
* @param _owner address of the token owner
*/
function buy(uint256 _tokenId, address _owner) public payable {
require(nifter.getIsForSale(_tokenId, _owner) == true, "bid::not for sale");
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// Check that the person who set the price still owns the token.
require(
_priceSetterStillOwnsTheToken(_tokenId, _owner),
"buy::Current token owner must be the person to have the latest price."
);
uint8 priceType = nifter.getPriceType(_tokenId, _owner);
require(priceType == 0, "buy is only allowed for fixed sale");
SalePrice memory sp = salePrice[_tokenId][_owner];
// Check that token is for sale.
require(sp.amount > 0, "buy::Tokens priced at 0 are not for sale.");
// Check that enough ether was sent.
require(
tokenPriceFeeIncluded(_tokenId, _owner) == msg.value,
"buy::Must purchase the token for the correct price"
);
// Wipe the token price.
_resetTokenPrice(_tokenId, _owner);
// Transfer token.
erc1155.safeTransferFrom(_owner, msg.sender, _tokenId, 1, '');
// if the buyer had an existing bid, return it
if (_addressHasBidOnToken(msg.sender, _tokenId, _owner)) {
_refundBid(_tokenId, _owner);
}
// Payout all parties.
address payable marketOwner = _makePayable(owner());
Payments.payout(
sp.amount,
!iMarketplaceSettings.hasTokenSold(_tokenId),
nifter.getServiceFee(_tokenId),
iERC1155CreatorRoyalty.getTokenRoyaltyPercentage(
_tokenId
),
iMarketplaceSettings.getERC1155ContractPrimarySaleFeePercentage(),
_makePayable(_owner),
marketOwner,
iERC1155CreatorRoyalty.tokenCreator(_tokenId),
marketOwner
);
// Set token as sold
iMarketplaceSettings.markERC1155Token(_tokenId, true);
//remove from sale after buy
nifter.removeFromSale(_tokenId, _owner);
emit Sold(msg.sender, _owner, sp.amount, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// tokenPrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Gets the sale price of the token
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
* @return uint256 sale price of the token
*/
function tokenPrice(uint256 _tokenId, address _owner)
external
view
returns (uint256)
{
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// TODO: Make sure to write test to verify that this returns 0 when it fails
if (_priceSetterStillOwnsTheToken(_tokenId, _owner)) {
return salePrice[_tokenId][_owner].amount;
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
// tokenPriceFeeIncluded
/////////////////////////////////////////////////////////////////////////
/**
* @dev Gets the sale price of the token including the marketplace fee.
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
* @return uint256 sale price of the token including the fee.
*/
function tokenPriceFeeIncluded(uint256 _tokenId, address _owner)
public
view
returns (uint256)
{
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// TODO: Make sure to write test to verify that this returns 0 when it fails
if (_priceSetterStillOwnsTheToken(_tokenId, _owner)) {
return
salePrice[_tokenId][_owner].amount.add(
salePrice[_tokenId][_owner].amount.mul(
nifter.getServiceFee(_tokenId)
).div(100)
);
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
// setInitialBidPriceWithRange
/////////////////////////////////////////////////////////////////////////
/**
* @dev set
* @param _bidAmount uint256 value in wei to bid.
* @param _startTime end time of bid
* @param _endTime end time of bid
* @param _owner address of the token owner
* @param _tokenId uint256 ID of the token
*/
function setInitialBidPriceWithRange(uint256 _bidAmount, uint256 _startTime, uint256 _endTime, address _owner, uint256 _tokenId) external override {
require(_bidAmount > 0, "setInitialBidPriceWithRange::Cannot bid 0 Wei.");
senderMustBeTokenOwner(_tokenId);
activeBid[_tokenId][_owner] = ActiveBid(
payable(_owner),
nifter.getServiceFee(_tokenId),
_bidAmount
);
_setBidRange(_startTime, _endTime, _tokenId, _owner);
emit SetInitialBidPriceWithRange(_bidAmount, _startTime, _endTime, _owner, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// bid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Bids on the token, replacing the bid if the bid is higher than the current bid. You cannot bid on a token you already own.
* @param _newBidAmount uint256 value in wei to bid.
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function bid(
uint256 _newBidAmount,
uint256 _tokenId,
address _owner
) external payable {
// Check that bid is greater than 0.
require(_newBidAmount > 0, "bid::Cannot bid 0 Wei.");
require(nifter.getIsForSale(_tokenId, _owner) == true, "bid::not for sale");
// Check that bid is higher than previous bid
uint256 currentBidAmount =
activeBid[_tokenId][_owner].amount;
require(
_newBidAmount > currentBidAmount &&
_newBidAmount >=
currentBidAmount.add(
currentBidAmount.mul(minimumBidIncreasePercentage).div(100)
),
"bid::Must place higher bid than existing bid + minimum percentage."
);
// Check that enough ether was sent.
uint256 requiredCost =
_newBidAmount.add(
_newBidAmount.mul(
nifter.getServiceFee(_tokenId)
).div(100)
);
require(
requiredCost <= msg.value,
"bid::Must purchase the token for the correct price."
);
//Check bid range
ActiveBidRange memory range = activeBidRange[_tokenId][_owner];
uint8 priceType = nifter.getPriceType(_tokenId, _owner);
require(priceType == 1 || priceType == 2, "bid is not valid for fixed sale");
if (priceType == 1)
require(range.startTime < block.timestamp && range.endTime > block.timestamp, "bid::can't place bid'");
// Check that bidder is not owner.
require(_owner != msg.sender, "bid::Bidder cannot be owner.");
// Refund previous bidder.
_refundBid(_tokenId, _owner);
// Set the new bid.
_setBid(_newBidAmount, msg.sender, _tokenId, _owner);
nifter.setBid(_newBidAmount, msg.sender, _tokenId, _owner);
emit Bid(msg.sender, _newBidAmount, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// safeAcceptBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Accept the bid on the token with the expected bid amount.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei amount of the bid
* @param _owner address of the token owner
*/
function safeAcceptBid(
uint256 _tokenId,
uint256 _amount,
address _owner
) external {
// Make sure accepting bid is the expected amount
require(
activeBid[_tokenId][_owner].amount == _amount,
"safeAcceptBid::Bid amount must equal expected amount"
);
acceptBid(_tokenId, _owner);
}
/////////////////////////////////////////////////////////////////////////
// acceptBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Accept the bid on the token.
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function acceptBid(uint256 _tokenId, address _owner) public {
// The sender must be the token owner
senderMustBeTokenOwner(_tokenId);
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// Check that a bid exists.
require(
_tokenHasBid(_tokenId, _owner),
"acceptBid::Cannot accept a bid when there is none."
);
// Get current bid on token
ActiveBid memory currentBid =
activeBid[_tokenId][_owner];
// Wipe the token price and bid.
_resetTokenPrice(_tokenId, _owner);
_resetBid(_tokenId, _owner);
// Transfer token.
erc1155.safeTransferFrom(msg.sender, currentBid.bidder, _tokenId, 1, '');
// Payout all parties.
address payable marketOwner = _makePayable(owner());
Payments.payout(
currentBid.amount,
!iMarketplaceSettings.hasTokenSold(_tokenId),
nifter.getServiceFee(_tokenId),
iERC1155CreatorRoyalty.getTokenRoyaltyPercentage(
_tokenId
),
iMarketplaceSettings.getERC1155ContractPrimarySaleFeePercentage(),
msg.sender,
marketOwner,
iERC1155CreatorRoyalty.tokenCreator(_tokenId),
marketOwner
);
iMarketplaceSettings.markERC1155Token(_tokenId, true);
uint256 serviceFee = currentBid.amount.mul(currentBid.marketplaceFee).div(100);
bidBalance[currentBid.bidder] = bidBalance[currentBid.bidder].sub(currentBid.amount.add(serviceFee));
//remove from sale after accepting the bid
nifter.removeFromSale(_tokenId, _owner);
emit AcceptBid(
currentBid.bidder,
msg.sender,
currentBid.amount,
_tokenId
);
}
/////////////////////////////////////////////////////////////////////////
// cancelBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Cancel the bid on the token.
* @param _tokenId uint256 ID of the token.
* @param _owner address of the token owner
*/
function cancelBid(uint256 _tokenId, address _owner) external {
// Check that sender has a current bid.
require(
_addressHasBidOnToken(msg.sender, _tokenId, _owner),
"cancelBid::Cannot cancel a bid if sender hasn't made one."
);
// Refund the bidder.
_refundBid(_tokenId, _owner);
emit CancelBid(
msg.sender,
activeBid[_tokenId][_owner].amount,
_tokenId
);
}
/////////////////////////////////////////////////////////////////////////
// currentBidDetailsOfToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Function to get current bid and bidder of a token.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function currentBidDetailsOfToken(uint256 _tokenId, address _owner)
public
view
returns (uint256, address)
{
return (
activeBid[_tokenId][_owner].amount,
activeBid[_tokenId][_owner].bidder
);
}
/////////////////////////////////////////////////////////////////////////
// _priceSetterStillOwnsTheToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Checks that the token is owned by the same person who set the sale price.
* @param _tokenId uint256 id of the.
* @param _owner address of the token owner
*/
function _priceSetterStillOwnsTheToken(
uint256 _tokenId,
address _owner
) internal view returns (bool) {
return
_owner ==
salePrice[_tokenId][_owner].seller;
}
/////////////////////////////////////////////////////////////////////////
// _resetTokenPrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set token price to 0 for a given contract.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _resetTokenPrice(uint256 _tokenId, address _owner)
internal
{
salePrice[_tokenId][_owner] = SalePrice(address(0), 0);
}
/////////////////////////////////////////////////////////////////////////
// _addressHasBidOnToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function see if the given address has an existing bid on a token.
* @param _bidder address that may have a current bid.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _addressHasBidOnToken(
address _bidder,
uint256 _tokenId,
address _owner)
internal view returns (bool) {
return activeBid[_tokenId][_owner].bidder == _bidder;
}
/////////////////////////////////////////////////////////////////////////
// _tokenHasBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function see if the token has an existing bid.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _tokenHasBid(
uint256 _tokenId,
address _owner)
internal
view
returns (bool)
{
return activeBid[_tokenId][_owner].bidder != address(0);
}
/////////////////////////////////////////////////////////////////////////
// _refundBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to return an existing bid on a token to the
* bidder and reset bid.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _refundBid(uint256 _tokenId, address _owner) internal {
ActiveBid memory currentBid =
activeBid[_tokenId][_owner];
if (currentBid.bidder == address(0)) {
return;
}
//current bidder should not be owner
if (bidBalance[currentBid.bidder] > 0 && currentBid.bidder != _owner)
{
Payments.refund(
currentBid.marketplaceFee,
currentBid.bidder,
currentBid.amount
);
//subtract bid balance
uint256 serviceFee = currentBid.amount.mul(currentBid.marketplaceFee).div(100);
bidBalance[currentBid.bidder] = bidBalance[currentBid.bidder].sub(currentBid.amount.add(serviceFee));
}
_resetBid(_tokenId, _owner);
}
/////////////////////////////////////////////////////////////////////////
// _resetBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to reset bid by setting bidder and bid to 0.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _resetBid(uint256 _tokenId, address _owner) internal {
activeBid[_tokenId][_owner] = ActiveBid(
address(0),
0,
0
);
}
/////////////////////////////////////////////////////////////////////////
// _setBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set a bid.
* @param _amount uint256 value in wei to bid. Does not include marketplace fee.
* @param _bidder address of the bidder.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _setBid(
uint256 _amount,
address payable _bidder,
uint256 _tokenId,
address _owner
) internal {
// Check bidder not 0 address.
require(_bidder != address(0), "Bidder cannot be 0 address.");
// Set bid.
activeBid[_tokenId][_owner] = ActiveBid(
_bidder,
nifter.getServiceFee(_tokenId),
_amount
);
//add bid balance
uint256 serviceFee = _amount.mul(nifter.getServiceFee(_tokenId)).div(100);
bidBalance[_bidder] = bidBalance[_bidder].add(_amount.add(serviceFee));
}
/////////////////////////////////////////////////////////////////////////
// _setBidRange
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set a bid range.
* @param _startTime start time UTC.
* @param _endTime end Time range.
* @param _tokenId uin256 id of the token.
*/
function _setBidRange(
uint256 _startTime,
uint256 _endTime,
uint256 _tokenId,
address _owner
) internal {
activeBidRange[_tokenId][_owner] = ActiveBidRange(_startTime, _endTime);
}
/////////////////////////////////////////////////////////////////////////
// _makePayable
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set a bid.
* @param _address non-payable address
* @return payable address
*/
function _makePayable(address _address)
internal
pure
returns (address payable)
{
return address(uint160(_address));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./SendValueOrEscrow.sol";
/**
* @title Payments contract for Nifter Marketplaces.
*/
contract Payments is SendValueOrEscrow {
using SafeMath for uint256;
using SafeMath for uint8;
/////////////////////////////////////////////////////////////////////////
// refund
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to refund an address. Typically for canceled bids or offers.
* Requirements:
*
* - _payee cannot be the zero address
*
* @param _marketplacePercentage uint8 percentage of the fee for the marketplace.
* @param _amount uint256 value to be split.
* @param _payee address seller of the token.
*/
function refund(
uint8 _marketplacePercentage,
address payable _payee,
uint256 _amount
) internal {
require(
_payee != address(0),
"refund::no payees can be the zero address"
);
if (_amount > 0) {
SendValueOrEscrow.sendValueOrEscrow(
_payee,
_amount.add(
calcPercentagePayment(_amount, _marketplacePercentage)
)
);
}
}
/////////////////////////////////////////////////////////////////////////
// payout
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to pay the seller, creator, and maintainer.
* Requirements:
*
* - _marketplacePercentage + _royaltyPercentage + _primarySalePercentage <= 100
* - no payees can be the zero address
*
* @param _amount uint256 value to be split.
* @param _isPrimarySale bool of whether this is a primary sale.
* @param _marketplacePercentage uint8 percentage of the fee for the marketplace.
* @param _royaltyPercentage uint8 percentage of the fee for the royalty.
* @param _primarySalePercentage uint8 percentage primary sale fee for the marketplace.
* @param _payee address seller of the token.
* @param _marketplacePayee address seller of the token.
* @param _royaltyPayee creater address .
* @param _primarySalePayee address seller of the token.
*/
function payout(
uint256 _amount,
bool _isPrimarySale,
uint8 _marketplacePercentage,
uint8 _royaltyPercentage,
uint8 _primarySalePercentage,
address payable _payee,
address payable _marketplacePayee,
address payable _royaltyPayee,
address payable _primarySalePayee
) internal {
require(
_marketplacePercentage <= 100,
"payout::marketplace percentage cannot be above 100"
);
require(
_royaltyPercentage.add(_primarySalePercentage) <= 100,
"payout::percentages cannot go beyond 100"
);
require(
_payee != address(0) &&
_primarySalePayee != address(0) &&
_marketplacePayee != address(0) &&
_royaltyPayee != address(0),
"payout::no payees can be the zero address"
);
// Note:: Solidity is kind of terrible in that there is a limit to local
// variables that can be put into the stack. The real pain is that
// one can put structs, arrays, or mappings into memory but not basic
// data types. Hence our payments array that stores these values.
uint256[4] memory payments;
// uint256 marketplacePayment
payments[0] = calcPercentagePayment(_amount, _marketplacePercentage);
// uint256 royaltyPayment
payments[1] = calcRoyaltyPayment(
_isPrimarySale,
_amount,
_royaltyPercentage
);
// uint256 primarySalePayment
payments[2] = calcPrimarySalePayment(
_isPrimarySale,
_amount,
_primarySalePercentage
);
// uint256 payeePayment
payments[3] = _amount.sub(payments[1]).sub(payments[2]);
// marketplacePayment
if (payments[0] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_marketplacePayee, payments[0]);
}
// royaltyPayment
if (payments[1] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_royaltyPayee, payments[1]);
}
// primarySalePayment
if (payments[2] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_primarySalePayee, payments[2]);
}
// payeePayment
if (payments[3] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_payee, payments[3]);
}
}
/////////////////////////////////////////////////////////////////////////
// calcRoyaltyPayment
/////////////////////////////////////////////////////////////////////////
/**
* @dev Private function to calculate Royalty amount.
* If primary sale: 0
* If no royalty percentage: 0
* otherwise: royalty in wei
* @param _isPrimarySale bool of whether this is a primary sale
* @param _amount uint256 value to be split
* @param _percentage uint8 royalty percentage
* @return uint256 wei value owed for royalty
*/
function calcRoyaltyPayment(
bool _isPrimarySale,
uint256 _amount,
uint8 _percentage
) private pure returns (uint256) {
if (_isPrimarySale) {
return 0;
}
return calcPercentagePayment(_amount, _percentage);
}
/////////////////////////////////////////////////////////////////////////
// calcPrimarySalePayment
/////////////////////////////////////////////////////////////////////////
/**
* @dev Private function to calculate PrimarySale amount.
* If not primary sale: 0
* otherwise: primary sale in wei
* @param _isPrimarySale bool of whether this is a primary sale
* @param _amount uint256 value to be split
* @param _percentage uint8 royalty percentage
* @return uint256 wei value owed for primary sale
*/
function calcPrimarySalePayment(
bool _isPrimarySale,
uint256 _amount,
uint8 _percentage
) private pure returns (uint256) {
if (_isPrimarySale) {
return calcPercentagePayment(_amount, _percentage);
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
// calcPercentagePayment
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to calculate percentage value.
* @param _amount uint256 wei value
* @param _percentage uint8 percentage
* @return uint256 wei value based on percentage.
*/
function calcPercentagePayment(uint256 _amount, uint8 _percentage)
internal
pure
returns (uint256)
{
return _amount.mul(_percentage).div(100);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/payment/PullPayment.sol";
import "./MaybeSendValue.sol";
/**
* @dev Contract to make payments. If a direct transfer fails, it will store the payment in escrow until the address decides to pull the payment.
*/
contract SendValueOrEscrow is MaybeSendValue, PullPayment {
/////////////////////////////////////////////////////////////////////////
// Events
/////////////////////////////////////////////////////////////////////////
event SendValue(address indexed _payee, uint256 amount);
/////////////////////////////////////////////////////////////////////////
// sendValueOrEscrow
/////////////////////////////////////////////////////////////////////////
/**
* @dev Send some value to an address.
* @param _to address to send some value to.
* @param _value uint256 amount to send.
*/
function sendValueOrEscrow(address payable _to, uint256 _value) internal {
// attempt to make the transfer
bool successfulTransfer = MaybeSendValue.maybeSendValue(_to, _value);
// if it fails, transfer it into escrow for them to redeem at their will.
if (!successfulTransfer) {
_asyncTransfer(_to, _value);
}
emit SendValue(_to, _value);
}
}
// SPDX-License-Identifier: MI
pragma solidity 0.6.12;
import "./ISendValueProxy.sol";
/**
* @dev Contract that attempts to send value to an address.
*/
contract SendValueProxy is ISendValueProxy {
/**
* @dev Send some wei to the address.
* @param _to address to send some value to.
*/
function sendValue(address payable _to) external payable override {
// Note that `<address>.transfer` limits gas sent to receiver. It may
// not support complex contract operations in the future.
_to.transfer(msg.value);
}
}
// 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
pragma solidity >=0.6.0 <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
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./escrow/Escrow.sol";
/**
* @dev Simple implementation of a
* https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
* strategy, where the paying contract doesn't interact directly with the
* receiver account, which must withdraw its payments itself.
*
* Pull-payments are often considered the best practice when it comes to sending
* Ether, security-wise. It prevents recipients from blocking execution, and
* eliminates reentrancy concerns.
*
* 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].
*
* To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
* instead of Solidity's `transfer` function. Payees can query their due
* payments with {payments}, and retrieve them with {withdrawPayments}.
*/
abstract contract PullPayment {
Escrow private _escrow;
constructor () internal {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated payments, forwarding all gas to the recipient.
*
* Note that _any_ account can call this function, not just the `payee`.
* This means that contracts unaware of the `PullPayment` protocol can still
* receive funds this way, by having a separate account call
* {withdrawPayments}.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee Whose payments will be withdrawn.
*/
function withdrawPayments(address payable payee) public virtual {
_escrow.withdraw(payee);
}
/**
* @dev Returns the payments owed to an address.
* @param dest The creditor's address.
*/
function payments(address dest) public view returns (uint256) {
return _escrow.depositsOf(dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* Funds sent in this way are stored in an intermediate {Escrow} contract, so
* there is no danger of them being spent before withdrawal.
*
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal virtual {
_escrow.deposit{ value: amount }(dest);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../math/SafeMath.sol";
import "../../access/Ownable.sol";
import "../../utils/Address.sol";
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
*
* Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the `Escrow` rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its owner, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Ownable {
using SafeMath for uint256;
using Address for address payable;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public payable virtual onlyOwner {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee, forwarding all gas to the
* recipient.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public virtual onlyOwner {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.sendValue(payment);
emit Withdrawn(payee, payment);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.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 IERC1155 is IERC165 {
/**
* @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
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 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;
}
}
| / _makePayable/ Internal function to set a bid. _address non-payable address return payable address/ | function _makePayable(address _address)
internal
pure
returns (address payable)
{
return address(uint160(_address));
}
| 1,455,531 |
./full_match/4/0xC6916b8BA3FAfD849bb8066d56E767815f587C56/sources/Users/scottferreira/Desktop/DevSAF/Companies/cmdR/cmdR_Consulting/Clients/Polyient/Subsidiaries/Polyient_Gaming/Development/particle-bridge/xgp5-testing/contracts/ParticleBridge.sol | All generations are the same for now | function getTokenGeneration(uint256) public pure returns (uint256) {
return 0;
}
| 12,315,578 |
pragma solidity ^0.4.19;
contract FrikandelToken {
address public contractOwner = msg.sender; //King Frikandel
bool public ICOEnabled = true; //Enable selling new Frikandellen
bool public Killable = true; //Enabled when the contract can commit suicide (In case of a problem with the contract in its early development, we will set this to false later on)
mapping (address => uint256) balances; //This is where de lekkere frikandellen are stored
mapping (address => mapping (address => uint256)) allowed; //This is where approvals are stored!
uint256 internal airdropLimit = 450000; //The maximum amount of tokens to airdrop before the feature shuts down
uint256 public airdropSpent = 0; //The amount of airdropped tokens given away (The airdrop will not send past this)
//uint256 internal ownerDrop = 50000; //Lets not waste gas storing this solid value we will only use 1 time - Adding it here so its obvious though
uint256 public totalSupply = 500000; //We're reserving the airdrop tokens, they will be spent eventually. Combining that with the ownerDrop tokens we're at 500k
uint256 internal hardLimitICO = 750000; //Do not allow more then 750k frikandellen to exist, ever. (The ICO will not sell past this)
function name() public pure returns (string) { return "Frikandel"; } //Frikandellen zijn lekker
function symbol() public pure returns (string) { return "FRIKANDEL"; } //I was deciding between FRKNDL and FRIKANDEL, but since the former is already kinda long why not just write it in full
function decimals() public pure returns (uint8) { return 0; } //Imagine getting half of a frikandel, that must be pretty shitty... Lets not do that. Whish we could store this as uint256 to save gas though lol
function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; }
function FrikandelToken() public {
balances[contractOwner] = 50000; //To use for rewards and such - also I REALLY like frikandellen so don't judge please
Transfer(0x0, contractOwner, 50000); //Run a Transfer event for this as recommended by the ERC20 spec.
}
function transferOwnership(address _newOwner) public {
require(msg.sender == contractOwner); //:crying_tears_of_joy:
contractOwner = _newOwner; //Nieuwe eigennaar van de frikandellentent
}
function Destroy() public {
require(msg.sender == contractOwner); //yo what why
if (Killable == true){ //Only if the contract is killable.. Go ahead
selfdestruct(contractOwner);
}
}
function disableSuicide() public returns (bool success){
require(msg.sender == contractOwner); //u dont control me
Killable = false; //The contract is now solid and will for ever be on the chain
return true;
}
function Airdrop(address[] _recipients) public {
require(msg.sender == contractOwner); //no airdrop access 4 u
if((_recipients.length + airdropSpent) > airdropLimit) { revert(); } //Hey, you're sending too much!!
for (uint256 i = 0; i < _recipients.length; i++) {
balances[_recipients[i]] += 1; //One frikandelletje 4 u
}
airdropSpent += _recipients.length; //Store the amount of tokens that have been given away. Doing this once instead of in the loop saves a neat amount of gas! (If the code gets intreupted it gets reverted anyways)
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //Useful if someone allowed you to spend some of their frikandellen or if a smart contract needs to interact with it! :)
//if (msg.data.length < (3 * 32) + 4) { revert(); } - Been thinking about implementing this, but its not fair to waste gas just to potentially ever save someone from sending a dumb malformed transaction, as a fault of their code or systems. (ERC20 Short address migration)
if (_value == 0) { Transfer(msg.sender, _to, 0); return; } //Follow the ERC20 spec and just mark the transfer event even through 0 tokens are being transfered
//bool sufficientFunds = balances[_from] >= _value; (Not having this single use variable in there saves us 8 gas)
//bool sufficientAllowance = allowed[_from][msg.sender] >= _value;
if (allowed[_from][msg.sender] >= _value && balances[_from] >= _value) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; } //ERC20 spec tells us the feature SHOULD throw() if the account has not authhorized the sender of the message, however I see everyone using return false... As its not a MUST to throw(), I'm going with the others and returning false
}
function approve(address _spender, uint256 _value) public returns (bool success) { //Allow someone else to spend some of your frikandellen
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } //ERC20 Spend/Approval race conditional migration - Always have a tx set the allowance to 0 first, before applying a new amount.
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
if (allowed[msg.sender][_spender] >= allowed[msg.sender][_spender] + _addedValue) { revert(); } //Lets not overflow the allowance ;) (I guess this also prevents it from being increased by 0 as a nice extra)
allowed[msg.sender][_spender] += _addedValue;
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
//if (msg.data.length < (2 * 32) + 4) { revert(); } - Been thinking about implementing this, but its not fair to waste gas just to potentially ever save someone from sending a dumb malformed transaction, as a fault of their code or systems. (ERC20 Short address migration)
if (_value == 0) { Transfer(msg.sender, _to, 0); return; } //Follow the ERC20 specification and just trigger the event and quit the function since nothing is being transfered anyways
//bool sufficientFunds = balances[msg.sender] >= _value; (Not having this single use variable in there saves us 8 gas)
//bool overflowed = balances[_to] + _value < balances[_to]; (Not having this one probably saves some too but I'm too lazy to test how much we save so fuck that)
if (balances[msg.sender] >= _value && !(balances[_to] + _value < balances[_to])) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true; //Smakelijk!
} else { return false; } //Sorry man je hebt niet genoeg F R I K A N D E L L E N
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function enableICO() public {
require(msg.sender == contractOwner); //Bro stay of my contract
ICOEnabled = true;
}
function disableICO() public {
require(msg.sender == contractOwner); //BRO what did I tell you
ICOEnabled = false; //Business closed y'all
}
function() payable public {
require(ICOEnabled);
require(msg.value > 0); //You can't send nothing lol. It won't get you anything and I won't allow you to waste your precious gas on it! (You can send 1wei though, which will give you nothing in return either but still run the code below)
if(balances[msg.sender]+(msg.value / 1e14) > 50000) { revert(); } //This would give you more then 50000 frikandellen, you can't buy from this account anymore through the ICO (If you eat 50000 frikandellen you'd probably die for real from all the layers of fat)
if(totalSupply+(msg.value / 1e14) > hardLimitICO) { revert(); } //Hard limit on Frikandellen
contractOwner.transfer(msg.value); //Thank you very much for supporting, I'll promise that I will spend an equal amount of money on purchaching frikandellen from my local store!
uint256 tokensIssued = (msg.value / 1e14); //Since 1 token can be bought for 0.0001 ETH split the value (in Wei) through 1e14 to get the amount of tokens
totalSupply += tokensIssued; //Lets note the tokens
balances[msg.sender] += tokensIssued; //Dinner is served (Or well, maybe just a snack... Kinda depends on how many frikandel you've bought)
Transfer(address(this), msg.sender, tokensIssued); //Trigger a transfer() event :)
}
} | Useful if someone allowed you to spend some of their frikandellen or if a smart contract needs to interact with it! :) | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { | 905,686 |
./full_match/97/0xccb4651211dE317551C38ED499c4e09d56F604dc/sources/project_/contracts/Libraries/LibMarket.sol | address payable receiver = royalties[i].account; address payable receiver = royalties[i].account; | function executeBid(
piMarket.TokenMeta storage meta,
piMarket.BidOrder storage bids,
LibShare.Share[] memory royalties,
LibShare.Share[] memory validatorRoyalties,
address feeAddress
) external {
require(msg.sender == meta.currentOwner);
require(!bids.withdrawn);
require(meta.status);
meta.status = false;
meta.price = bids.price;
bids.withdrawn = true;
if (meta.currency == address(0)) {
uint256 sum = bids.price;
uint256 fee = bids.price / 100;
for (uint256 i = 0; i < royalties.length; i++) {
uint256 amount = (royalties[i].value * bids.price) / 10000;
(bool royalSuccess, ) = payable(royalties[i].account).call{
value: amount
}("");
require(royalSuccess, "Royalty transfer failed");
sum = sum - amount;
}
for (uint256 i = 0; i < validatorRoyalties.length; i++) {
uint256 amount = (validatorRoyalties[i].value * bids.price) / 10000;
(bool royalSuccess, ) = payable(validatorRoyalties[i].account).call{
value: amount
}("");
require(royalSuccess, "Royalty transfer failed");
sum = sum - amount;
}
require(isSuccess, "Transfer failed");
require(feeSuccess, "Fee Transfer failed");
uint256 sum = bids.price;
uint256 fee = bids.price / 100;
for (uint256 i = 0; i < royalties.length; i++) {
uint256 amount = (royalties[i].value * bids.price) / 10000;
bool royalSuccess = IERC20(meta.currency)
.transfer(royalties[i].account, amount);
require(royalSuccess, "Royalty transfer failed");
sum = sum - amount;
}
for (uint256 i = 0; i < validatorRoyalties.length; i++) {
uint256 amount = (validatorRoyalties[i].value * bids.price) / 10000;
(bool royalValSuccess) = IERC20(meta.currency).transfer(validatorRoyalties[i].account, amount);
require(royalValSuccess, "Royalty transfer failed");
sum = sum - amount;
}
bool isSuccess = IERC20(meta.currency).transfer(
meta.currentOwner,
sum - fee
);
require(isSuccess, "Transfer failed");
(bool feeSuccess) = IERC20(meta.currency).transfer(
feeAddress,
fee
);
require(feeSuccess, "Fee Transfer failed");
}
}
| 3,276,809 |
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;
}
}
//import "openzeppelin-eth/contracts/ownership/Ownable.sol";
//pragma solidity ^0.4.24;
//import "zos-lib/contracts/Initializable.sol";
//pragma solidity >=0.4.24 <0.6.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
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 use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool wasInitializing = initializing;
initializing = true;
initialized = true;
_;
initializing = wasInitializing;
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// 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.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @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 is Initializable {
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.
*/
function initialize(address sender) public initializer {
_owner = 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;
}
uint256[50] private ______gap;
}
//import "openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol";
//pragma solidity ^0.4.24;
//import "./IERC20.sol";
//pragma solidity ^0.4.24;
/**
* @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 Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string name, string symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
//import "./lib/SafeMathInt.sol";
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, 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.
*/
//pragma solidity 0.4.24;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a)
internal
pure
returns (int256)
{
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
/**
* @title uFragments ERC20 token
* @dev This is part of an implementation of the uFragments Ideal Money protocol.
* uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and
* combining tokens proportionally across all wallets.
*
* uFragment balances are internally represented with a hidden denomination, 'gons'.
* We support splitting the currency in expansion and combining the currency on contraction by
* changing the exchange rate between the hidden 'gons' and the public 'fragments'.
*/
contract UFragments is ERC20Detailed, Ownable {
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
// Anytime there is division, there is a risk of numerical instability from rounding errors. In
// order to minimize this risk, we adhere to the following guidelines:
// 1) The conversion rate adopted is the number of gons that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert gons to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Gon balances converted into Fragments are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will
// be decreased by precisely x Fragments, and B's external balance will be precisely
// increased by x Fragments.
//
// We do not guarantee that the sum of all balances equals the result of calling totalSupply().
// This is because, for any conversion function 'f()' that has non-zero rounding error,
// f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
bool private rebasePausedDeprecated;
bool private tokenPausedDeprecated;
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 50 * 10**6 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Fragments, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
external
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
// From this point forward, _gonsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
function initialize(address owner_)
public
initializer
{
ERC20Detailed.initialize("AmpleForthGold", "AAU", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePausedDeprecated = false;
tokenPausedDeprecated = false;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[owner_] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
emit Transfer(address(0x0), owner_, _totalSupply);
}
/**
* @return The total number of fragments.
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @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)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
}
//import "./RebaseDelta.sol";
//pragma solidity >=0.4.24;
//import '@uniswap/v2-periphery/contracts/libraries/SafeMath.sol';
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library RB_SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
function div(uint x, uint y) internal pure returns (uint) {
require(y != 0);
return x / y;
}
}
library RB_UnsignedSafeMath {
function add(int x, int y) internal pure returns (int z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(int x, int y) internal pure returns (int z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(int x, int y) internal pure returns (int z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
function div(int x, int y) internal pure returns (int) {
require(y != 0);
return x / y;
}
}
//import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint 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 (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint 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 (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
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 (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes /* calldata */ data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/** Calculates the Delta for a rebase based on the ratio
*** between the price of two different token pairs on
*** Uniswap
***
*** - minimalist design
*** - low gas design
*** - free for anyone to call.
***
****/
contract RebaseDelta {
using RB_SafeMath for uint256;
using RB_UnsignedSafeMath for int256;
uint256 private constant PRICE_PRECISION = 10**9;
function getPrice(IUniswapV2Pair pair_, bool flip_)
public
view
returns (uint256)
{
require(address(pair_) != address(0));
(uint256 reserves0, uint256 reserves1, ) = pair_.getReserves();
if (flip_) {
(reserves0, reserves1) = (reserves1, reserves0);
}
// reserves0 = base (probably ETH/WETH)
// reserves1 = token of interest (maybe ampleforthgold or paxusgold etc)
// multiply to equate decimals, multiply up to PRICE_PRECISION
uint256 price = (reserves1.mul(PRICE_PRECISION)).div(reserves0);
return price;
}
// calculates the supply delta for moving the price of token X to the price
// of token Y (with the understanding that they are both priced in a common
// tokens value, i.e. WETH).
function calculate(IUniswapV2Pair X_,
bool flipX_,
uint256 decimalsX_,
uint256 SupplyX_,
IUniswapV2Pair Y_,
bool flipY_,
uint256 decimalsY_)
public
view
returns (int256)
{
uint256 px = getPrice(X_, flipX_);
require(px != uint256(0));
uint256 py = getPrice(Y_, flipY_);
require(py != uint256(0));
uint256 targetSupply = (SupplyX_.mul(py)).div(px);
// adust for decimals
if (decimalsX_ == decimalsY_) {
// do nothing
}
else if (decimalsX_ > decimalsY_) {
uint256 ddg = (10**decimalsX_).div(10**decimalsY_);
require (ddg != uint256(0));
targetSupply = targetSupply.mul(ddg);
}
else {
uint256 ddl = (10**decimalsY_).div(10**decimalsX_);
require (ddl != uint256(0));
targetSupply = targetSupply.div(ddl);
}
int256 delta = int256(SupplyX_).sub(int256(targetSupply));
return delta;
}
}
//==Developed and deployed by the AmpleForthGold Team: https://ampleforth.gold
// With thanks to:
// https://github.com/Auric-Goldfinger
// https://github.com/z0sim0s
// https://github.com/Aurum-hub
/**
* @title Orchestrator
* @notice The orchestrator is the main entry point for rebase operations. It coordinates the rebase
* actions with external consumers (price oracles) and provides timing / access control for when a
* rebase occurs.
*
* Orchestrator is based on Ampleforth.org implmentation with modifications by the AmpleForthgold team.
* It is a merge and modification of the Orchestrator.sol and UFragmentsPolicy.sol from the original
* Ampleforth project. Thanks to the Ampleforth.org team!
*
* Code ideas also come from the RMPL.IO (RAmple Project), YAM team and BASED team.
* Thanks to the all whoose ideas we stole!
*
* We have simplifed the design to lower the gas fees. In some places we have removed things that were
* "nice to have" because of the cost of GAS. Specifically we have lowered the number of events and
* hard coded things that we know are going to be constant (such as not looking up a uniswap pair,
* we just pass the pair pointer into the contract). This was done to save GAS and lower the execution
* cost of the contract.
*
* The Price used for rebase calculations shall be sourced from Uniswap (on chain liquidity pools).
*
* Relying on price Oracles (either on chain or off chain) will never be perfect. Oracles go bad,
* others come good. At present we will use liquidity pools on uniswap to provide the oracles
* for pricing. However those oracles may go bad and need to be replaced. We think that oracle
* failure in the short term is unlikly, but not impossible. In the long term it may be likely
* to see oracle failure. Due to this the contract 'owners' (the AmpleForthGold team) shall
* have an 'off switch' in the code to disable and override rebase operations. At some point
* it may be needed...but we hope it is not needed.
*
*/
contract Orchestrator is Ownable {
using SafeMath for uint16;
using SafeMath for uint256;
using SafeMathInt for int256;
// The ERC20 Token for ampleforthgold
UFragments public afgToken = UFragments(0x8E54954B3Bbc07DbE3349AEBb6EAFf8D91Db5734);
// oracle configuration - see RebaseDelta.sol for details.
RebaseDelta public oracle = RebaseDelta(0xF09402111AF6409B410A8Dd07B82F1cd1674C55F);
IUniswapV2Pair public tokenPairX = IUniswapV2Pair(0x2d0C51C1282c31d71F035E15770f3214e20F6150);
IUniswapV2Pair public tokenPairY = IUniswapV2Pair(0x9C4Fe5FFD9A9fC5678cFBd93Aa2D4FD684b67C4C);
bool public flipX = false;
bool public flipY = false;
uint8 public decimalsX = 9;
uint8 public decimalsY = 9;
// The timestamp of the last rebase event generated from this contract.
// Technically another contract cauld also cause a rebase event,
// so this cannot be relied on globally. uint64 should not clock
// over in forever.
uint64 public lastRebase = uint64(0);
// The number of rebase cycles since inception. Why the original
// designers did not keep this inside uFragments is a question
// that really deservers an answer? We can use a uint16 cause we
// will be about 179 years old before it clocks over.
uint16 public epoch = 3;
// Transactions are used to generate call back to DEXs that need to be
// informed about rebase events. Specifically with uniswap the function
// on the IUniswapV2Pair.sync() needs to be called so that the
// liquidity pool can reset it reserves to the correct value.
// ...Stable transaction ordering is not guaranteed.
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(address indexed destination, uint index, bytes data);
Transaction[] public transactions;
/**
* Just initializes the base class.
*/
constructor()
public {
Ownable.initialize(msg.sender);
}
/**
* @notice Owner entry point to initiate a rebase operation.
* @param supplyDelta the delta as passed to afgToken.rebase.
* (the delta needs to be calulated off chain or by the
* calling contract).
* @param disable_ passing true will disable the ability of
* users (other then the owner) to cause a rebase.
*
* The owner can always generate a rebase operation. At some point in the future
* the owners keys shall be burnt. However at this time (and until we are certain
* everthing is working as it should) the owners shall keep their keys.
* The ability for the owners to generate a rebase of any value at any time is a
* carry over from the original ampleforth project. This function is just a little
* more direct.
*/
function ownerForcedRebase(int256 supplyDelta, bool disable_)
external
onlyOwner
{
/* If lastrebase is set to 0 then *users* cannot cause a rebase.
* This should allow the owner to disable the auto-rebase operations if
* things go wrong (see things go wrong above). */
if (disable_) {
lastRebase = uint64(0);
} else {
lastRebase = uint64(block.timestamp);
}
afgToken.rebase(epoch.add(1), supplyDelta);
popTransactionList();
}
/**
* @notice Main entry point to initiate a rebase operation.
* On success returns the new supply value.
*/
function rebase()
external
returns (uint256)
{
// The owner shall call this member for the following reasons:
// (1) Something went wrong and we need a rebase now!
// (2) At some random time at least 24 hours, but no more then 48
// hours after the last rebase.
if (Ownable.isOwner())
{
return internal_rebase();
}
// we require at least 1 owner rebase event prior to being enabled!
require (lastRebase != uint64(0));
// at least 24 hours shall have passed since the last rebase event.
require (lastRebase + 1 days < uint64(block.timestamp));
// if more then 48 hours have passed then allow a rebase from anyone
// willing to pay the GAS.
if (lastRebase + 2 days < uint64(block.timestamp))
{
return internal_rebase();
}
// There is (currently) no way of generating a random number in a
// contract that cannot be seen/used by the miner. Thus a big miner
// could use information on a rebase for their advantage. We do not
// want to give any advantage to a big miner over a little trader,
// thus the traders ability to generate and see a rebase (ahead of time)
// should be about the same as a that of a large miners.
//
// If (in the future) the ability to provide true randomeness
// changes then we would like to re-write this bit of code to provide
// true random rebases where no one gets an advantage.
//
// A day after the last rebase, anyone can call this rebase function
// to generate a rebase. However to give it a little bit of complexity
// and mildly lower the ability of traders/miners to take advantage
// of the rebase we will set the *fair* odds of a rebase() call
// succeeding at 20%. Of course it can still be gamed, but this
// makes gaming it just that little bit harder.
//
// MINERS: To game it the miner would need to adjust his coinbase to
// correctly solve the xor with the preceeding block hashs,
// That is do-able, but the miner would need to go out of there
// way to do it...but no perfect solutions so this is it at the
// moment.
//
// TRADERS: To game it they could just call this function many times
// until it triggers. They have a 20% chance of triggering each
// time they call it. They could get lucky, or they could burn a lot of
// GAS. Whatever they do it will be obvious from the many calls to this
// function.
uint256 odds = uint256(blockhash(block.number - 1)) ^ uint256(block.coinbase);
if ((odds % uint256(5)) == uint256(1))
{
return internal_rebase();
}
// no change, no rebase!
return uint256(0);
}
/**
* @notice Internal entry point to initiate a rebase operation.
* If we get here then a rebase call to the erc20 token
* will occur.
*
* returns the new supply value.
*/
function internal_rebase()
private
returns(uint256) {
lastRebase = uint64(block.timestamp);
uint256 z = afgToken.rebase(epoch.add(1), calculateRebaseDelta(true));
popTransactionList();
return z;
}
/**
* @notice Configures the oracle & information passed to the oracle
* to calculate the rebase. See RebaseDelta for definition
* of params.
*
* Initially tokenPairX is the uniswap pair for AAU/WETH
* and tokenPairY is the uniswap pair for PAXG/WETH.
* These addresses can be verified on etherscan.io.
*/
function configureOracle(IUniswapV2Pair tokenPairX_,
bool flipX_,
uint8 decimalsX_,
IUniswapV2Pair tokenPairY_,
bool flipY_,
uint8 decimalsY_,
RebaseDelta oracle_)
external
onlyOwner
{
tokenPairX = tokenPairX_;
flipX = flipX_;
decimalsX = decimalsX_;
tokenPairY = tokenPairY_;
flipY = flipY_;
decimalsY = decimalsY_;
oracle = oracle_;
}
/**
* @notice tries to calculate a rebase based on the configured oracle info.
*
* @param limited_ passing true will limit the rebase based on the 5% rule.
*/
function calculateRebaseDelta(bool limited_)
public
view
returns (int256)
{
require (afgToken != UFragments(0));
require (oracle != RebaseDelta(0));
require (tokenPairX != IUniswapV2Pair(0));
require (tokenPairY != IUniswapV2Pair(0));
require (decimalsX != uint8(0));
require (decimalsY != uint8(0));
uint256 supply = afgToken.totalSupply();
int256 delta = - oracle.calculate(
tokenPairX,
flipX,
decimalsX,
supply,
tokenPairY,
flipY,
decimalsY);
if (!limited_) {
// Unlimited (brutal) rebase.
return delta;
}
if (delta == int256(0))
{
// no rebase needed!
return int256(0);
}
/** 5% rules:
* (1) If the price is in the +-5% range do not rebase at all. This
* allows the market to fix the price to within a 10% range.
* (2) If the price is within +-10% range then only rebase by 1%.
* (3) If the price is more then +-10% then the change shall be half the
* delta. i.e. if the price diff is -28% then the change will be -14%.
*/
int256 supply5p = int256(supply.div(uint256(20))); // 5% == 5/100 == 1/20
if (delta < int256(0)) {
if (-delta < supply5p) {
return int256(0); // no rebase: 5% rule (1)
}
if (-delta < supply5p.mul(int256(2))) {
return (-supply5p).div(int256(5)); // -1% rebase
}
} else {
if (delta < supply5p) {
return int256(0); // no rebase: 5% rule (1)
}
if (delta < supply5p.mul(int256(2))) {
return supply5p.div(int256(5)); // +1% rebase
}
}
return (delta.div(2)); // half delta rebase
}
// for testing purposes only!
// winds back time a day at a time.
function windbacktime()
public
onlyOwner {
require (lastRebase > 1 days);
lastRebase-= 1 days;
}
//===TRANSACTION FUNCTIONALITY (mostly identical to original Ampleforth implementation)
/* generates callbacks after a rebase */
function popTransactionList()
private
{
// we are getting an AAU price feed from this uniswap pair, thus when the rebase occurs
// we need to ask it to rebase the AAU tokens in the pair. We always know this needs
// to be done, so no use making a transcation for it.
if (tokenPairX != IUniswapV2Pair(0)) {
tokenPairX.sync();
}
// iterate thru other interested parties and generate a call to update their
// contracts.
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");
}
}
}
}
/**
* @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 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 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(
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB)
// + callValueTransferGas (9000) + callNewAccountGas
// (25000, in case the destination address does not exist and needs creating)
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;
}
} | Converts to absolute value, and fails on overflow./ | function abs(int256 a)
internal
pure
returns (int256)
{
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
| 131,743 |
./partial_match/56/0x0aa63FB3A93110ff1C57dBaCF13E69b641352F80/sources/StrategymeowthLPV2.sol | Swaps {meowth} for {lpToken0}, {lpToken1} & {wbnb} using PancakeSwap./ | function addLiquidity() internal {
uint256 meowthHalf = IERC20(meowth).balanceOf(address(this)).div(2);
if (lpToken0 != meowth) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
meowthHalf,
0,
meowthToLp0Route,
address(this),
now.add(600)
);
}
if (lpToken1 != meowth) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
meowthHalf,
0,
meowthToLp1Route,
address(this),
now.add(600)
);
}
uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this));
uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this));
IPancakeRouter(unirouter).addLiquidity(
lpToken0,
lpToken1,
lp0Bal,
lp1Bal,
1,
1,
address(this),
now.add(600)
);
}
| 11,225,312 |
/**
*Submitted for verification at Etherscan.io on 2021-11-13
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
}
}
/**
* @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);
}
}
/**
* @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;
}
}
/**
* @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 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 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 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 Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_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
_beforeTokenTransfer(owner, address(0), tokenId);
// 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");
_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 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 Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
/**
* @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);
}
/**
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*
*/
contract SolaStars is ERC721, ReentrancyGuard, Ownable
{
using SafeMath for uint256;
uint256 public max_tokens_per_transaction = 2;
uint256 public token_price = 200000000000000000;
uint256 public max_token_supply = 2000;
uint256 public starting_index_block;
uint256 public starting_index;
bool public whitelist_sale_active = false;
bool public public_raffle_sale_active = false;
bool public general_sale_active = false;
string public provenance_hash = "";
/**
* @dev Nothing to see here.
*/
constructor() ERC721("The SolaVerse: SOLA-STARS", "SOLA-STAR") {}
/**
* @dev Whitelisted method to mint a free token.
*
* @param _signature bytes memory
* @param _id string memory
* @param _timestamp string memory
*/
function mintStarWhitelist(bytes memory _signature, string memory _id, string memory _timestamp) public nonReentrant
{
require(whitelist_sale_active, "Whitelist not open");
require(isWalletAuthorisedToMint(msg.sender, _signature, _id, _timestamp, "Whitelist"), "Not authorised to mint");
require(IERC721(address(this)).balanceOf(msg.sender) == 0, "Wallet has already minted");
maybeMintTokens(1);
}
/**
* @dev Whitelisted method to mint a free token and one additional token at normal price.
*
* @param _signature bytes memory
* @param _id string memory
* @param _timestamp string memory
*/
function mintStarsWhitelist(bytes memory _signature, string memory _id, string memory _timestamp) public payable nonReentrant
{
require(whitelist_sale_active, "Whitelist not open");
require(msg.value >= token_price, "Not enough ETH");
require(isWalletAuthorisedToMint(msg.sender, _signature, _id, _timestamp, "Whitelist"), "Not authorised to mint");
require(IERC721(address(this)).balanceOf(msg.sender) == 0, "Wallet has already minted");
maybeMintTokens(2);
}
/**
* @dev Public payable method to mint the number of tokens requested based on the results of the public raffle.
*
* @param _num_tokens uint256
* @param _signature bytes memory
* @param _id string memory
* @param _timestamp string memory
*/
function mintStarRaffle(uint256 _num_tokens, bytes memory _signature, string memory _id, string memory _timestamp) public payable nonReentrant
{
require(public_raffle_sale_active, "Public Raffle not open");
require(msg.value >= (token_price * _num_tokens), "Not enough ETH");
require(isWalletAuthorisedToMint(msg.sender, _signature, _id, _timestamp, "Public-Raffle"), "Not authorised to mint");
require(IERC721(address(this)).balanceOf(msg.sender) == 0, "Wallet has already minted");
maybeMintTokens(_num_tokens);
}
/**
* @dev Public payable method to mint the number of tokens requested.
*
* @param _num_tokens uint256
*/
function mintStarPublic(uint256 _num_tokens) public payable nonReentrant
{
require(general_sale_active, "General sale not open");
require(msg.value >= (token_price * _num_tokens), "Not enough ETH");
maybeMintTokens(_num_tokens);
}
/**
* @dev Mint the requested number of tokens if there's enough available.
* @dev If we haven't set the starting index yet and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block.
*/
function maybeMintTokens(uint _num_tokens) internal
{
require((_num_tokens > 0) && (_num_tokens <= max_tokens_per_transaction), "Cannot mint that many tokens");
require(totalSupply().add(_num_tokens) <= max_token_supply, "Exceeds max tokens available");
for (uint256 i=0; i<_num_tokens; i++)
{
uint256 new_token_id = totalSupply();
_safeMint(msg.sender, new_token_id);
}
if (starting_index_block == 0 && (totalSupply() == max_token_supply))
{
starting_index_block = block.number;
}
}
/**
* @dev Use ECDSA to get the wallet info from the signature and check to make sure it matches the current sender's wallet.
*
* @param _wallet address
* @param _signature bytes memory
* @param _id string memory
* @param _timestamp string memory
* @param _sale string memory
* @return bool
*/
function isWalletAuthorisedToMint(address _wallet, bytes memory _signature, string memory _id, string memory _timestamp, string memory _sale) public pure returns(bool)
{
return ECDSA.recover(ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked("Token-", bytes(_sale), "-Mint--", bytes(_id), "--", bytes(_timestamp), "."))), _signature) == _wallet;
}
/**
* @dev Finalize starting index.
*/
function finalizeStartingIndex() public
{
require(starting_index == 0, "Starting index already set");
require(starting_index_block != 0, "Starting index block not set");
starting_index = uint256(blockhash(starting_index_block)) % max_token_supply;
if (block.number.sub(starting_index_block) > 255)
{
starting_index = uint256(blockhash(block.number-1)) % max_token_supply;
}
if (starting_index == 0)
{
starting_index = starting_index.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking setting starting index.
*/
function emergencySetStartingIndexBlock() public onlyOwner
{
require(starting_index == 0, "Starting index is already set");
starting_index_block = block.number;
}
/**
* @dev Set provenance once it's calculated.
*
* @param _provenance_hash string memory
*/
function setProvenanceHash(string memory _provenance_hash) public onlyOwner
{
provenance_hash = _provenance_hash;
}
/**
* @dev Set the base URI to a new value once we reveal the tokens.
*
* @param _new_token_base_uri string memory
*/
function setBaseURI(string memory _new_token_base_uri) public onlyOwner
{
_setBaseURI(_new_token_base_uri);
}
/**
* @dev Set the flag to enable/disable the Whitelist sale.
*/
function setWhitelistSaleActive(bool _active) public onlyOwner
{
whitelist_sale_active = _active;
}
/**
* @dev Set the flag to enable/disable the Public Raffle sale.
*/
function setPublicRaffleSaleActive(bool _active) public onlyOwner
{
public_raffle_sale_active = _active;
}
/**
* @dev Set the flag to enable/disable the General sale.
*/
function setGeneralSaleActive(bool _active) public onlyOwner
{
general_sale_active = _active;
}
/**
* @dev Allow owner withdrawal from the main wallet.
*/
function withdraw() public onlyOwner
{
uint256 balance = address(this).balance;
require(balance > 0, "Balance is 0");
payable(msg.sender).transfer(balance);
}
}
/**
* @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;
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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(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);
}
}
/**
* @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;
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", 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));
}
}
/**
* @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;
}
}
/**
* @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 {
using EnumerableSet for EnumerableSet.Bytes32Set;
// 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 Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @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) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @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) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @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._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.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) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @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) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, 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) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @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) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// 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))));
}
} | Set the flag to enable/disable the Whitelist sale./ | function setWhitelistSaleActive(bool _active) public onlyOwner
{
whitelist_sale_active = _active;
}
| 10,697,533 |
//Address: 0x89fd8971fef41923ee6f1416c1fbaf5fe6698eea
//Contract name: PlatoPresale
//Balance: 0 Ether
//Verification Date: 9/15/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.13;
contract token {
function transfer(address receiver, uint amount);
function balanceOf(address _owner) constant returns (uint256 balance);
}
contract PlatoPresale {
address public beneficiary;
uint public min_fundingGoal;
uint public max_fundingGoal;
uint public amountRaised;
uint public deadline;
uint public start;
uint public rate;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
event GoalReached(address beneficiary, uint amountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
bool crowdsaleClosed = false;
/* data structure to hold information about campaign contributors */
/* at initialization, setup the owner */
function PlatoPresale() {
beneficiary = msg.sender;
min_fundingGoal = 100 * 1 ether;
max_fundingGoal = 2000 * 1 ether;
start = now + 10 * 1 hours;
deadline = start + 30 * 1 days;
rate = 1500; // Each ether exchange for 1500.00000000 PAT
tokenReward = token(0x432fFe79337cBaA1B921c7d0802e4ADe89F474E5);
}
/* The function without name is the default function that is called whenever anyone sends funds to a contract */
function () payable{
uint amount = msg.value;
require (now >= start);
require (!crowdsaleClosed);
require (amountRaised + amount <= max_fundingGoal);
require (amount >= 5 * 1 ether);
balanceOf[msg.sender] += amount;
amountRaised += amount;
tokenReward.transfer(msg.sender, amount * rate * 10 ** 8 / 1 ether);
if(amountRaised >= min_fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
modifier MaxGoalHit() { if (amountRaised >= max_fundingGoal - 10 ether) _; }
/* checks if the goal or time limit has been reached and ends the campaign */
function checkGoalReached() afterDeadline {
if (amountRaised >= min_fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
function safeWithdrawal() afterDeadline {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
FundTransfer(msg.sender, amount, false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (beneficiary.send(amountRaised)) {
FundTransfer(beneficiary, amountRaised, false);
} else {
//If we fail to send the funds to beneficiary, unlock funders balance
fundingGoalReached = false;
}
}
}
function GoalHitWithdrawl() MaxGoalHit {
require(msg.sender == beneficiary);
if (beneficiary.send(amountRaised)) {
crowdsaleClosed = true;
FundTransfer(beneficiary, amountRaised, false);
} else {
//If we fail to send the funds to beneficiary, unlock funders balance
fundingGoalReached = false;
}
}
}
| data structure to hold information about campaign contributors / at initialization, setup the owner / | function PlatoPresale() {
beneficiary = msg.sender;
min_fundingGoal = 100 * 1 ether;
max_fundingGoal = 2000 * 1 ether;
start = now + 10 * 1 hours;
deadline = start + 30 * 1 days;
tokenReward = token(0x432fFe79337cBaA1B921c7d0802e4ADe89F474E5);
}
| 15,863,726 |
pragma solidity ^0.4.25;
/**
*
12HourTrains - 3% every 12 hours. Want to get quick ETH? Try our new Dice game.
https://12hourtrains.github.io/
Version 3
*/
contract TwelveHourTrains {
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) referrer;
uint256 public step = 100;
uint256 public minimum = 10 finney;
uint256 public stakingRequirement = 2 ether;
address public ownerWallet;
address public owner;
uint256 private randNonce = 0;
/**
* @dev Modifiers
*/
modifier onlyOwner()
{
require(msg.sender == owner);
_;
}
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
/**
* @dev Event
*/
event Invest(address investor, uint256 amount);
event Withdraw(address investor, uint256 amount);
event Bounty(address hunter, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Lottery(address player, uint256 lotteryNumber, uint256 amount, uint256 result,bool isWin);
/**
* @dev Сonstructor Sets the original roles of the contract
*/
constructor() public
{
owner = msg.sender;
ownerWallet = msg.sender;
}
/**
* @dev Allows current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
* @param newOwnerWallet The address to transfer ownership to.
*/
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner
{
require(newOwner != address(0));
owner = newOwner;
ownerWallet = newOwnerWallet;
emit OwnershipTransferred(owner, newOwner);
}
/**
* @dev Investments
*/
function () public payable
{
buy(0x0);
}
function buy(address _referredBy) public payable
{
require(msg.value >= minimum);
address _customerAddress = msg.sender;
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
investments[_referredBy] >= stakingRequirement
){
// wealth redistribution
referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(5).div(100));
}
if (investments[msg.sender] > 0){
if (withdraw()){
withdrawals[msg.sender] = 0;
}
}
investments[msg.sender] = investments[msg.sender].add(msg.value);
joined[msg.sender] = block.timestamp;
ownerWallet.transfer(msg.value.mul(5).div(100));
emit Invest(msg.sender, msg.value);
}
//--------------------------------------------------------------------------------------------
// LOTTERY
//--------------------------------------------------------------------------------------------
/**
* @param _value number in array [1,2,3]
*/
function lottery(uint256 _value) public payable disableContract
{
uint256 random = getRandomNumber(msg.sender) + 1;
bool isWin = false;
if (random == _value) {
isWin = true;
uint256 prize = msg.value.mul(249).div(100);
if (prize <= address(this).balance) {
msg.sender.transfer(prize);
}
}
ownerWallet.transfer(msg.value.mul(5).div(100));
emit Lottery(msg.sender, _value, msg.value, random, isWin);
}
/**
* @dev Evaluate current balance
* @param _address Address of investor
*/
function getBalance(address _address) view public returns (uint256) {
uint256 minutesCount = now.sub(joined[_address]).div(1 minutes);
uint256 percent = investments[_address].mul(step).div(100);
uint256 different = percent.mul(minutesCount).div(24000);
uint256 balance = different.sub(withdrawals[_address]);
return balance;
}
/**
* @dev Withdraw dividends from contract
*/
function withdraw() public returns (bool){
require(joined[msg.sender] > 0);
uint256 balance = getBalance(msg.sender);
if (address(this).balance > balance){
if (balance > 0){
withdrawals[msg.sender] = withdrawals[msg.sender].add(balance);
msg.sender.transfer(balance);
emit Withdraw(msg.sender, balance);
}
return true;
} else {
return false;
}
}
/**
* @dev Bounty reward
*/
function bounty() public {
uint256 refBalance = checkReferral(msg.sender);
if(refBalance >= minimum) {
if (address(this).balance > refBalance) {
referrer[msg.sender] = 0;
msg.sender.transfer(refBalance);
emit Bounty(msg.sender, refBalance);
}
}
}
/**
* @dev Gets balance of the sender address.
* @return An uint256 representing the amount owned by the msg.sender.
*/
function checkBalance() public view returns (uint256) {
return getBalance(msg.sender);
}
/**
* @dev Gets withdrawals of the specified address.
* @param _investor The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function checkWithdrawals(address _investor) public view returns (uint256)
{
return withdrawals[_investor];
}
/**
* @dev Gets investments of the specified address.
* @param _investor The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function checkInvestments(address _investor) public view returns (uint256)
{
return investments[_investor];
}
/**
* @dev Gets referrer balance of the specified address.
* @param _hunter The address of the referrer
* @return An uint256 representing the referral earnings.
*/
function checkReferral(address _hunter) public view returns (uint256)
{
return referrer[_hunter];
}
function checkContractBalance() public view returns (uint256)
{
return address(this).balance;
}
//----------------------------------------------------------------------------------
// INTERNAL FUNCTION
//----------------------------------------------------------------------------------
function getRandomNumber(address _addr) private returns(uint256 randomNumber)
{
randNonce++;
randomNumber = uint256(keccak256(abi.encodePacked(now, _addr, randNonce, block.coinbase, block.number))) % 3;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
} | Allows current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to. newOwnerWallet The address to transfer ownership to./ | function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner
{
require(newOwner != address(0));
owner = newOwner;
ownerWallet = newOwnerWallet;
emit OwnershipTransferred(owner, newOwner);
}
| 9,916,901 |
./partial_match/1/0x8189B58a9debA68B2753c66e383afAf33759C145/sources/GCCDiscrete.sol | Owner's method to manually tick next checkpoint./ | function tickNext() public onlyOwner returns (bool) {
return _tickNext();
}
| 4,095,063 |
// simple faucet
//
// @authors:
// Cody Burns <[email protected]>
// license: Apache 2.0
// version: 0.3.0
pragma solidity ^0.4.19;
contract owned{
function owned () public {
owner = msg.sender;
}
address owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract faucet is owned {
////////////////
//Global VARS//////////////////////////////////////////////////////////////////////////
//////////////
/* int */
uint public lastDrip;
uint public dropValue;
uint public runningCount;
uint public blockTarget;
int public difficulty;
int parentDiff;
modifier PoWcheck( address value, bytes32 nonce ){
require(sha256( value , block.number, nonce ) <= bytes32(difficulty));
_;
}
///////////
//EVENTS////////////////////////////////////////////////////////////////////////////
//////////
event Payouts(address rewarded, uint drip);
event DripSet(uint dripset);
event Donation(address coolperson, uint paid);
event NewDiff(int _foo, int _bar, int pd, bytes32 difficulty);
//////////////
//Operations////////////////////////////////////////////////////////////////////////
//////////////
/* init */
function faucet(uint _dropValue) public {
dropValue = _dropValue;
runningCount = 0;
lastDrip = now;
owner = msg.sender;
difficulty = int256(21258703883413520253546235528938795582436286247207447304119165813952801144832) ;
blockTarget = 300;
}
function max(int a, int b) private pure returns (int) {
return a > b ? a : b;
}
/* public */
function () public payable{
Donation(msg.sender, msg.value);
}
function getETC( address _payout, bytes32 nonce ) public PoWcheck( _payout, nonce ) {
require(newDiff());
_payout.transfer( dropValue );
runningCount += dropValue;
Payouts(_payout, dropValue);
}
/* onlyOwner */
function dripSet ( uint _dropValue, int _difficulty, uint _blockTarget ) public onlyOwner{
dropValue = _dropValue;
difficulty = _difficulty;
blockTarget = _blockTarget;
DripSet(dropValue);
}
function newDiff() internal returns( bool ) {
// adjust PoW to target the blocktarget
parentDiff = difficulty;
int foo = max( (1 - ( int(now) - int(lastDrip) ) % int(blockTarget)), -99 );
int bar = 2048 * foo;
int pd = parentDiff % bar;
difficulty = parentDiff + bar;
lastDrip = now;
NewDiff(foo, bar, pd, bytes32(difficulty));
return(true);
}
function selfTest( address value, bytes32 nonce )
public
view
returns ( byte status , bool isPoW, bytes32 hash, bytes32 diff ){
hash = sha256( value , block.number, nonce );
isPoW = hash < bytes32(difficulty);
diff = bytes32(difficulty);
return ( hex'01', isPoW, hash, diff ) ;
}
////////////
//SAFETY ////////////////////////////////////////////////////////////////////
//////////
//safety switches consider removing for production
//clean up after contract is no longer needed
function killshot() onlyOwner public {
selfdestruct( owner );
}
}
| adjust PoW to target the blocktarget | function newDiff() internal returns( bool ) {
parentDiff = difficulty;
int foo = max( (1 - ( int(now) - int(lastDrip) ) % int(blockTarget)), -99 );
int bar = 2048 * foo;
int pd = parentDiff % bar;
difficulty = parentDiff + bar;
lastDrip = now;
NewDiff(foo, bar, pd, bytes32(difficulty));
return(true);
}
| 1,046,560 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
/// @title: David Ariew X Tatler China
import "../ERC721ProjectUpgradeable.sol";
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// '########:::::'###::::'##::::'##:'####:'########::::::::'###::::'########::'####:'########:'##:::::'##::::'##::::'##::::'########::::'###::::'########:'##:::::::'########:'########::::::'######::'##::::'##:'####:'##::: ##::::'###:::: //
// ##.... ##:::'## ##::: ##:::: ##:. ##:: ##.... ##::::::'## ##::: ##.... ##:. ##:: ##.....:: ##:'##: ##::::. ##::'##:::::... ##..::::'## ##:::... ##..:: ##::::::: ##.....:: ##.... ##::::'##... ##: ##:::: ##:. ##:: ###:: ##:::'## ##::: //
// ##:::: ##::'##:. ##:: ##:::: ##:: ##:: ##:::: ##:::::'##:. ##:: ##:::: ##:: ##:: ##::::::: ##: ##: ##:::::. ##'##::::::::: ##:::::'##:. ##::::: ##:::: ##::::::: ##::::::: ##:::: ##:::: ##:::..:: ##:::: ##:: ##:: ####: ##::'##:. ##:: //
// ##:::: ##:'##:::. ##: ##:::: ##:: ##:: ##:::: ##::::'##:::. ##: ########::: ##:: ######::: ##: ##: ##::::::. ###:::::::::: ##::::'##:::. ##:::: ##:::: ##::::::: ######::: ########::::: ##::::::: #########:: ##:: ## ## ##:'##:::. ##: //
// ##:::: ##: #########:. ##:: ##::: ##:: ##:::: ##:::: #########: ##.. ##:::: ##:: ##...:::: ##: ##: ##:::::: ## ##::::::::: ##:::: #########:::: ##:::: ##::::::: ##...:::: ##.. ##:::::: ##::::::: ##.... ##:: ##:: ##. ####: #########: //
// ##:::: ##: ##.... ##::. ## ##:::: ##:: ##:::: ##:::: ##.... ##: ##::. ##::: ##:: ##::::::: ##: ##: ##::::: ##:. ##:::::::: ##:::: ##.... ##:::: ##:::: ##::::::: ##::::::: ##::. ##::::: ##::: ##: ##:::: ##:: ##:: ##:. ###: ##.... ##: //
// ########:: ##:::: ##:::. ###::::'####: ########::::: ##:::: ##: ##:::. ##:'####: ########:. ###. ###::::: ##:::. ##::::::: ##:::: ##:::: ##:::: ##:::: ########: ########: ##:::. ##::::. ######:: ##:::: ##:'####: ##::. ##: ##:::: ##: //
// ........:::..:::::..:::::...:::::....::........::::::..:::::..::..:::::..::....::........:::...::...::::::..:::::..::::::::..:::::..:::::..:::::..:::::........::........::..:::::..::::::......:::..:::::..::....::..::::..::..:::::..:: //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
contract DavidAriewXTatlerChina is ERC721ProjectUpgradeable {
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() public initializer {
_initialize("David Ariew X Tatler China", "DavidAriewXTatlerChina");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "./access/AdminControlUpgradeable.sol";
import "./core/ERC721ProjectCoreUpgradeable.sol";
/**
* @dev ERC721Project implementation
*/
abstract contract ERC721ProjectUpgradeable is
Initializable,
AdminControlUpgradeable,
ERC721Upgradeable,
ERC721ProjectCoreUpgradeable,
UUPSUpgradeable
{
function _initialize(string memory _name, string memory _symbol) internal initializer {
__AdminControl_init();
__ERC721_init(_name, _symbol);
__ERC721ProjectCore_init();
__UUPSUpgradeable_init();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
_approveTransfer(from, to, tokenId);
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev See {IProjectCore-registerManager}.
*/
function registerManager(address manager, string calldata baseURI)
external
override
adminRequired
nonBlacklistRequired(manager)
{
_registerManager(manager, baseURI, false);
}
/**
* @dev See {IProjectCore-registerManager}.
*/
function registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) external override adminRequired nonBlacklistRequired(manager) {
_registerManager(manager, baseURI, baseURIIdentical);
}
/**
* @dev See {IProjectCore-unregisterManager}.
*/
function unregisterManager(address manager) external override adminRequired {
_unregisterManager(manager);
}
/**
* @dev See {IProjectCore-blacklistManager}.
*/
function blacklistManager(address manager) external override adminRequired {
_blacklistManager(manager);
}
/**
* @dev See {IProjectCore-managerSetBaseTokenURI}.
*/
function managerSetBaseTokenURI(string calldata uri) external override managerRequired {
_managerSetBaseTokenURI(uri, false);
}
/**
* @dev See {IProjectCore-managerSetBaseTokenURI}.
*/
function managerSetBaseTokenURI(string calldata uri, bool identical) external override managerRequired {
_managerSetBaseTokenURI(uri, identical);
}
/**
* @dev See {IProjectCore-managerSetTokenURIPrefix}.
*/
function managerSetTokenURIPrefix(string calldata prefix) external override managerRequired {
_managerSetTokenURIPrefix(prefix);
}
/**
* @dev See {IProjectCore-managerSetTokenURI}.
*/
function managerSetTokenURI(uint256 tokenId, string calldata uri) external override managerRequired {
_managerSetTokenURI(tokenId, uri);
}
/**
* @dev See {IProjectCore-managerSetTokenURI}.
*/
function managerSetTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override managerRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint256 i = 0; i < tokenIds.length; i++) {
_managerSetTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {IProjectCore-setBaseTokenURI}.
*/
function setBaseTokenURI(string calldata uri) external override adminRequired {
_setBaseTokenURI(uri);
}
/**
* @dev See {IProjectCore-setTokenURIPrefix}.
*/
function setTokenURIPrefix(string calldata prefix) external override adminRequired {
_setTokenURIPrefix(prefix);
}
/**
* @dev See {IProjectCore-setTokenURI}.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired {
_setTokenURI(tokenId, uri);
}
/**
* @dev See {IProjectCore-setTokenURI}.
*/
function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override adminRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint256 i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {IProjectCore-setMintPermissions}.
*/
function setMintPermissions(address manager, address permissions) external override adminRequired {
_setMintPermissions(manager, permissions);
}
/**
* @dev See {IERC721ProjectCore-adminMint}.
*/
function adminMint(address to, string calldata uri)
external
virtual
override
nonReentrant
adminRequired
returns (uint256)
{
return _adminMint(to, uri);
}
/**
* @dev See {IERC721ProjectCore-adminMintBatch}.
*/
function adminMintBatch(address to, uint16 count)
external
virtual
override
nonReentrant
adminRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
tokenIds[i] = _adminMint(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721ProjectCore-adminMintBatch}.
*/
function adminMintBatch(address to, string[] calldata uris)
external
virtual
override
nonReentrant
adminRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](uris.length);
for (uint256 i = 0; i < uris.length; i++) {
tokenIds[i] = _adminMint(to, uris[i]);
}
return tokenIds;
}
/**
* @dev Mint token with no manager
*/
function _adminMint(address to, string memory uri) internal virtual returns (uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the manager that minted the token
_tokensManager[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721ProjectCore-managerMint}.
*/
function managerMint(address to, string calldata uri)
external
virtual
override
nonReentrant
managerRequired
returns (uint256)
{
return _managerMint(to, uri);
}
/**
* @dev See {IERC721ProjectCore-managerMintBatch}.
*/
function managerMintBatch(address to, uint16 count)
external
virtual
override
nonReentrant
managerRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
tokenIds[i] = _managerMint(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721ProjectCore-managerMintBatch}.
*/
function managerMintBatch(address to, string[] calldata uris)
external
virtual
override
nonReentrant
managerRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](uris.length);
for (uint256 i = 0; i < uris.length; i++) {
tokenIds[i] = _managerMint(to, uris[i]);
}
}
/**
* @dev Mint token via manager
*/
function _managerMint(address to, string memory uri) internal virtual returns (uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
_checkMintPermissions(to, tokenId);
// Track the manager that minted the token
_tokensManager[tokenId] = msg.sender;
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintManager(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721ProjectCore-tokenManager}.
*/
function tokenManager(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "Nonexistent token");
return _tokenManager(tokenId);
}
/**
* @dev See {IERC721ProjectCore-burn}.
*/
function burn(uint256 tokenId) public virtual override nonReentrant {
require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved");
address owner = ownerOf(tokenId);
_burn(tokenId);
_postBurn(owner, tokenId);
}
/**
* @dev See {IProjectCore-setRoyalties}.
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints)
external
override
adminRequired
{
_setRoyaltiesManager(address(this), receivers, basisPoints);
}
/**
* @dev See {IProjectCore-setRoyalties}.
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
require(_exists(tokenId), "Nonexistent token");
_setRoyalties(tokenId, receivers, basisPoints);
}
/**
* @dev See {IProjectCore-setRoyaltiesManager}.
*/
function setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
_setRoyaltiesManager(manager, receivers, basisPoints);
}
/**
* @dev {See IProjectCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory, uint256[] memory)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See IProjectCore-getFees}.
*/
function getFees(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory, uint256[] memory)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See IProjectCore-getFeeRecipients}.
*/
function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyReceivers(tokenId);
}
/**
* @dev {See IProjectCore-getFeeBps}.
*/
function getFeeBps(uint256 tokenId) external view virtual override returns (uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyBPS(tokenId);
}
/**
* @dev {See IProjectCore-royaltyInfo}.
*/
function royaltyInfo(
uint256 tokenId,
uint256 value,
bytes calldata
)
external
view
virtual
override
returns (
address,
uint256,
bytes memory
)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Nonexistent token");
return _tokenURI(tokenId);
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC721Upgradeable).interfaceId
|| interfaceId == type(IERC721MetadataUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. 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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// 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 {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.
*/
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
* publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
* continuation of the upgradability.
*
* The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./IAdminControlUpgradeable.sol";
abstract contract AdminControlUpgradeable is
Initializable,
OwnableUpgradeable,
IAdminControlUpgradeable,
ERC165Upgradeable
{
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// Track registered admins
EnumerableSetUpgradeable.AddressSet private _admins;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __AdminControl_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC165_init_unchained();
__AdminControl_init_unchained();
}
function __AdminControl_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return interfaceId == type(IAdminControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(isAdmin(_msgSender()), "AdminControl: Must be owner or admin");
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint256 i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (_admins.add(admin)) {
emit AdminApproved(admin, msg.sender);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.remove(admin)) {
emit AdminRevoked(admin, msg.sender);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public view override returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../managers/ERC721/IERC721ProjectApproveTransferManager.sol";
import "../managers/ERC721/IERC721ProjectBurnableManager.sol";
import "../permissions/ERC721/IERC721ProjectMintPermissions.sol";
import "./IERC721ProjectCoreUpgradeable.sol";
import "./ProjectCoreUpgradeable.sol";
/**
* @dev Core ERC721 project implementation
*/
abstract contract ERC721ProjectCoreUpgradeable is Initializable, ProjectCoreUpgradeable, IERC721ProjectCoreUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* @dev initializer
*/
function __ERC721ProjectCore_init() internal initializer {
__ProjectCore_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ERC721ProjectCore_init_unchained();
}
function __ERC721ProjectCore_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ProjectCoreUpgradeable, IERC165Upgradeable)
returns (bool)
{
return interfaceId == type(IERC721ProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IProjectCore-managerSetApproveTransfer}.
*/
function managerSetApproveTransfer(bool enabled) external override managerRequired {
require(
!enabled ||
ERC165CheckerUpgradeable.supportsInterface(
msg.sender,
type(IERC721ProjectApproveTransferManager).interfaceId
),
"Manager must implement IERC721ProjectApproveTransferManager"
);
if (_managerApproveTransfers[msg.sender] != enabled) {
_managerApproveTransfers[msg.sender] = enabled;
emit ManagerApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an manager
*/
function _setMintPermissions(address manager, address permissions) internal {
require(_managers.contains(manager), "ProjectCore: Invalid manager");
require(
permissions == address(0x0) ||
ERC165CheckerUpgradeable.supportsInterface(
permissions,
type(IERC721ProjectMintPermissions).interfaceId
),
"Invalid address"
);
if (_managerPermissions[manager] != permissions) {
_managerPermissions[manager] = permissions;
emit MintPermissionsUpdated(manager, permissions, msg.sender);
}
}
/**
* Check if an manager can mint
*/
function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_managerPermissions[msg.sender] != address(0x0)) {
IERC721ProjectMintPermissions(_managerPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
/**
* Override for post mint actions
*/
function _postMintBase(address, uint256) internal virtual {}
/**
* Override for post mint actions
*/
function _postMintManager(address, uint256) internal virtual {}
/**
* Post-burning callback and metadata cleanup
*/
function _postBurn(address owner, uint256 tokenId) internal virtual {
// Callback to originating manager if needed
if (_tokensManager[tokenId] != address(this)) {
if (
ERC165CheckerUpgradeable.supportsInterface(
_tokensManager[tokenId],
type(IERC721ProjectBurnableManager).interfaceId
)
) {
IERC721ProjectBurnableManager(_tokensManager[tokenId]).onBurn(owner, tokenId);
}
}
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Delete token origin manager tracking
delete _tokensManager[tokenId];
}
/**
* Approve a transfer
*/
function _approveTransfer(
address from,
address to,
uint256 tokenId
) internal {
if (_managerApproveTransfers[_tokensManager[tokenId]]) {
require(
IERC721ProjectApproveTransferManager(_tokensManager[tokenId]).approveTransfer(from, to, tokenId),
"ERC721Project: Manager approval failure"
);
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @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
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 IERC721ReceiverUpgradeable {
/**
* @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
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @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
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);
}
}
}
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature(
"upgradeTo(address)",
oldImplementation
)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/*
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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, "Address: low-level delegate call failed");
}
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);
}
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
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 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] = 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));
}
}
// SPDX-License-Identifier: MIT
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 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
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControlUpgradeable is IERC165Upgradeable {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your manager to approve a transfer
*/
interface IERC721ProjectApproveTransferManager is IERC165 {
/**
* @dev Set whether or not the project will check the manager for approval of token transfer
*/
function setApproveTransfer(address project, bool enabled) external;
/**
* @dev Called by project contract to approve a transfer
*/
function approveTransfer(
address from,
address to,
uint256 tokenId
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Your manager is required to implement this interface if it wishes
* to receive the onBurn callback whenever a token the manager created is
* burned
*/
interface IERC721ProjectBurnableManager is IERC165 {
/**
* @dev callback handler for burn events
*/
function onBurn(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721Project compliant manager contracts.
*/
interface IERC721ProjectMintPermissions is IERC165 {
/**
* @dev get approval to mint
*/
function approveMint(
address manager,
address to,
uint256 tokenId
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "./IProjectCoreUpgradeable.sol";
/**
* @dev Core ERC721 project interface
*/
interface IERC721ProjectCoreUpgradeable is IProjectCoreUpgradeable {
/**
* @dev mint a token with no manager. Can only be called by an admin. set uri to empty string to use default uri.
* Returns tokenId minted
*/
function adminMint(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token with no manager. Can only be called by an admin.
* Returns tokenId minted
*/
function adminMintBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token with no manager. Can only be called by an admin.
* Returns tokenId minted
*/
function adminMintBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered manager. set uri to "" to use default uri
* Returns tokenId minted
*/
function managerMint(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered manager.
* Returns tokenIds minted
*/
function managerMintBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered manager.
* Returns tokenId minted
*/
function managerMintBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered manager's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../managers/ProjectTokenURIManager/IProjectTokenURIManager.sol";
import "./IProjectCoreUpgradeable.sol";
/**
* @dev Core project implementation
*/
abstract contract ProjectCoreUpgradeable is
Initializable,
IProjectCoreUpgradeable,
ReentrancyGuardUpgradeable,
ERC165Upgradeable
{
using StringsUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
/**
* External interface identifiers for royalties
*/
/**
* @dev ProjectCore
*
* bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6
*
* => 0xbb3bafd6 = 0xbb3bafd6
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_PROJECTCORE = 0xbb3bafd6;
/**
* @dev Rarible: RoyaltiesV1
*
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
*
* => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
/**
* @dev Foundation
*
* bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c
*
* => 0xd5a06d4c = 0xd5a06d4c
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
/**
* @dev EIP-2981
*
* bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d
*
* => 0x6057361d = 0x6057361d
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d;
uint256 _tokenCount;
// Track registered managers data
EnumerableSetUpgradeable.AddressSet internal _managers;
EnumerableSetUpgradeable.AddressSet internal _blacklistedManagers;
mapping(address => address) internal _managerPermissions;
mapping(address => bool) internal _managerApproveTransfers;
// For tracking which manager a token was minted by
mapping(uint256 => address) internal _tokensManager;
// The baseURI for a given manager
mapping(address => string) private _managerBaseURI;
mapping(address => bool) private _managerBaseURIIdentical;
// The prefix for any tokens with a uri configured
mapping(address => string) private _managerURIPrefix;
// Mapping for individual token URIs
mapping(uint256 => string) internal _tokenURIs;
// Royalty configurations
mapping(address => address payable[]) internal _managerRoyaltyReceivers;
mapping(address => uint256[]) internal _managerRoyaltyBPS;
mapping(uint256 => address payable[]) internal _tokenRoyaltyReceivers;
mapping(uint256 => uint256[]) internal _tokenRoyaltyBPS;
/**
* @dev initializer
*/
function __ProjectCore_init() internal initializer {
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ProjectCore_init_unchained();
_tokenCount = 0;
}
function __ProjectCore_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IProjectCoreUpgradeable).interfaceId ||
super.supportsInterface(interfaceId) ||
interfaceId == _INTERFACE_ID_ROYALTIES_PROJECTCORE ||
interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE ||
interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION ||
interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
/**
* @dev Only allows registered managers to call the specified function
*/
modifier managerRequired() {
require(_managers.contains(msg.sender), "Must be registered manager");
_;
}
/**
* @dev Only allows non-blacklisted managers
*/
modifier nonBlacklistRequired(address manager) {
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
_;
}
/**
* @dev totalSupply
*/
function totalSupply() public view override returns (uint256) {
return _tokenCount;
}
/**
* @dev See {IProjectCore-getManagers}.
*/
function getManagers() external view override returns (address[] memory managers) {
managers = new address[](_managers.length());
for (uint256 i = 0; i < _managers.length(); i++) {
managers[i] = _managers.at(i);
}
return managers;
}
/**
* @dev Register an manager
*/
function _registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) internal {
require(manager != address(this), "Project: Invalid");
require(manager.isContract(), "Project: Manager must be a contract");
if (_managers.add(manager)) {
_managerBaseURI[manager] = baseURI;
_managerBaseURIIdentical[manager] = baseURIIdentical;
emit ManagerRegistered(manager, msg.sender);
}
}
/**
* @dev Unregister an manager
*/
function _unregisterManager(address manager) internal {
if (_managers.remove(manager)) {
emit ManagerUnregistered(manager, msg.sender);
}
}
/**
* @dev Blacklist an manager
*/
function _blacklistManager(address manager) internal {
require(manager != address(this), "Cannot blacklist yourself");
if (_managers.remove(manager)) {
emit ManagerUnregistered(manager, msg.sender);
}
if (_blacklistedManagers.add(manager)) {
emit ManagerBlacklisted(manager, msg.sender);
}
}
/**
* @dev Set base token uri for an manager
*/
function _managerSetBaseTokenURI(string calldata uri, bool identical) internal {
_managerBaseURI[msg.sender] = uri;
_managerBaseURIIdentical[msg.sender] = identical;
}
/**
* @dev Set token uri prefix for an manager
*/
function _managerSetTokenURIPrefix(string calldata prefix) internal {
_managerURIPrefix[msg.sender] = prefix;
}
/**
* @dev Set token uri for a token of an manager
*/
function _managerSetTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensManager[tokenId] == msg.sender, "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Set base token uri for tokens with no manager
*/
function _setBaseTokenURI(string memory uri) internal {
_managerBaseURI[address(this)] = uri;
}
/**
* @dev Set token uri prefix for tokens with no manager
*/
function _setTokenURIPrefix(string calldata prefix) internal {
_managerURIPrefix[address(this)] = prefix;
}
/**
* @dev Set token uri for a token with no manager
*/
function _setTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensManager[tokenId] == address(this), "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Retrieve a token's URI
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
address manager = _tokensManager[tokenId];
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
// 1. if tokenURI is stored in this contract, use it with managerURIPrefix if any
if (bytes(_tokenURIs[tokenId]).length != 0) {
if (bytes(_managerURIPrefix[manager]).length != 0) {
return string(abi.encodePacked(_managerURIPrefix[manager], _tokenURIs[tokenId]));
}
return _tokenURIs[tokenId];
}
// 2. if URI is controlled by manager, retrieve it from manager
if (ERC165CheckerUpgradeable.supportsInterface(manager, type(IProjectTokenURIManager).interfaceId)) {
return IProjectTokenURIManager(manager).tokenURI(address(this), tokenId);
}
// 3. use managerBaseURI with id or not
if (!_managerBaseURIIdentical[manager]) {
return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString()));
} else {
return _managerBaseURI[manager];
}
}
/**
* Get token manager
*/
function _tokenManager(uint256 tokenId) internal view returns (address manager) {
manager = _tokensManager[tokenId];
require(manager != address(this), "No manager for token");
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
return manager;
}
/**
* Helper to get royalties for a token
*/
function _getRoyalties(uint256 tokenId) internal view returns (address payable[] storage, uint256[] storage) {
return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId));
}
/**
* Helper to get royalty receivers for a token
*/
function _getRoyaltyReceivers(uint256 tokenId) internal view returns (address payable[] storage) {
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (_managerRoyaltyReceivers[_tokensManager[tokenId]].length > 0) {
return _managerRoyaltyReceivers[_tokensManager[tokenId]];
}
return _managerRoyaltyReceivers[address(this)];
}
/**
* Helper to get royalty basis points for a token
*/
function _getRoyaltyBPS(uint256 tokenId) internal view returns (uint256[] storage) {
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_managerRoyaltyBPS[_tokensManager[tokenId]].length > 0) {
return _managerRoyaltyBPS[_tokensManager[tokenId]];
}
return _managerRoyaltyBPS[address(this)];
}
function _getRoyaltyInfo(uint256 tokenId, uint256 value)
internal
view
returns (
address receiver,
uint256 amount,
bytes memory data
)
{
address payable[] storage receivers = _getRoyaltyReceivers(tokenId);
require(receivers.length <= 1, "More than 1 royalty receiver");
if (receivers.length == 0) {
return (address(this), 0, data);
}
return (receivers[0], (_getRoyaltyBPS(tokenId)[0] * value) / 10000, data);
}
/**
* Set royalties for a token
*/
function _setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint256 i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_tokenRoyaltyReceivers[tokenId] = receivers;
_tokenRoyaltyBPS[tokenId] = basisPoints;
emit RoyaltiesUpdated(tokenId, receivers, basisPoints);
}
/**
* Set royalties for all tokens of an manager
*/
function _setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint256 i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_managerRoyaltyReceivers[manager] = receivers;
_managerRoyaltyBPS[manager] = basisPoints;
if (manager == address(this)) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit ManagerRoyaltiesUpdated(manager, receivers, basisPoints);
}
}
uint256[36] private __gap;
}
// SPDX-License-Identifier: MIT
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
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Core project interface
*/
interface IProjectCoreUpgradeable is IERC165Upgradeable {
event ManagerRegistered(address indexed manager, address indexed sender);
event ManagerUnregistered(address indexed manager, address indexed sender);
event ManagerBlacklisted(address indexed manager, address indexed sender);
event MintPermissionsUpdated(address indexed manager, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ManagerRoyaltiesUpdated(address indexed manager, address payable[] receivers, uint256[] basisPoints);
event ManagerApproveTransferUpdated(address indexed manager, bool enabled);
/**
* @dev totalSupply
*/
function totalSupply() external view returns (uint256);
/**
* @dev gets address of all managers
*/
function getManagers() external view returns (address[] memory);
/**
* @dev add an manager. Can only be called by contract owner or admin.
* manager address must point to a contract implementing IProjectManager.
* Returns True if newly added, False if already added.
*/
function registerManager(address manager, string calldata baseURI) external;
/**
* @dev add an manager. Can only be called by contract owner or admin.
* manager address must point to a contract implementing IProjectManager.
* Returns True if newly added, False if already added.
*/
function registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) external;
/**
* @dev add an manager. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterManager(address manager) external;
/**
* @dev blacklist an manager. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified manager. It will also unregister the manager if needed.
* Returns True if removed, False if already removed.
*/
function blacklistManager(address manager) external;
/**
* @dev set the baseTokenURI of an manager. Can only be called by manager.
*/
function managerSetBaseTokenURI(string calldata uri) external;
/**
* @dev set the baseTokenURI of an manager. Can only be called by manager.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function managerSetBaseTokenURI(string calldata uri, bool identical) external;
/**
* @dev set the common prefix of an manager. Can only be called by manager.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function managerSetTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token manager. Can only be called by manager that minted token.
*/
function managerSetTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of a token manager for multiple tokens. Can only be called by manager that minted token.
*/
function managerSetTokenURI(uint256[] calldata tokenId, string[] calldata uri) external;
/**
* @dev set the baseTokenURI for tokens with no manager. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no manager. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no manager. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no manager. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external;
/**
* @dev set a permissions contract for an manager. Used to control minting.
*/
function setMintPermissions(address manager, address permissions) external;
/**
* @dev Configure so transfers of tokens created by the caller (must be manager) gets approval
* from the manager before transferring
*/
function managerSetApproveTransfer(bool enabled) external;
/**
* @dev get the manager of a given token
*/
function tokenManager(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Set royalties of an manager
*/
function setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint256[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(
uint256 tokenId,
uint256 value,
bytes calldata data
)
external
view
returns (
address,
uint256,
bytes memory
);
}
// SPDX-License-Identifier: MIT
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 initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165CheckerUpgradeable {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your manager to have overloadable URI's
*/
interface IProjectTokenURIManager is IERC165 {
/**
* Get the uri for a given project/tokenId
*/
function tokenURI(address project, uint256 tokenId) external view returns (string memory);
} | See {IERC721ProjectCore-managerMintBatch}./ | function managerMintBatch(address to, string[] calldata uris)
external
virtual
override
nonReentrant
managerRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](uris.length);
for (uint256 i = 0; i < uris.length; i++) {
tokenIds[i] = _managerMint(to, uris[i]);
}
}
| 12,006,230 |
./full_match/80001/0x99785826d26aC5811893f14C9935c58C49C959BD/sources/project_/contracts/AccessControl.sol | check if an account is a owner | function isOwner(address account) public view returns (bool) {
return _hasRole(OWNER, account);
}
| 5,634,813 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol";
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "./interfaces/ICToken.sol";
import "./utils/Controller.sol";
import "./token/Ticket.sol";
import "./yield-source-interactor/CompoundYieldSourceInteractor.sol";
contract CompoundPrizeLottery is
Controller,
Ownable,
CompoundYieldSourceInteractor,
VRFConsumerBaseV2
{
using Counters for Counters.Counter;
enum State {
OPEN,
CLOSED,
AWARDING_WINNER,
RANDOMNESS_FULFILLED
}
/* Lottery parameters */
uint256 public constant DRAWING_PERIOD = 10 days;
uint256 public constant MINIMUM_DEPOSIT = 1e18; // 1
/* Lottery parameters */
string public name;
Counters.Counter public lotteryId;
State public state;
uint256 public latestLotteryTimestamp;
/* Tokens */
Ticket internal ticket;
IERC20 internal token;
ICToken internal cToken;
/* Chainlink VRF parameters */
uint16 internal constant REQUEST_CONFIRMATIONS = 3;
uint32 internal constant NUM_WORDS = 1;
uint32 internal constant CALLBACK_GAS_LIMIT = 200000;
/* Chainlink VRF parameters */
VRFCoordinatorV2Interface internal immutable vrfCoordinator;
uint64 internal immutable subscriptionId;
bytes32 internal immutable keyHash;
uint256 internal randomNumber;
/* Events */
event LotteryStarted(
uint256 indexed lotteryId,
uint256 lotteryStart,
IERC20 token,
ICToken cToken
);
event ReserveSupplied(uint256 indexed lotteryId, uint256 amount);
event PlayerDeposited(
uint256 indexed lotteryId,
address indexed player,
uint256 amount
);
event PlayerRedeemed(
uint256 indexed lotteryId,
address indexed player,
uint256 amount
);
event RandomNumberRequested(
uint256 indexed lotteryId,
uint64 subscriptionId,
uint256 requestId
);
event RandomNumberReceived(
uint256 indexed lotteryId,
uint64 subscriptionId,
uint256 randomNumber
);
event LotteryWinnerAwarded(
uint256 indexed lotteryId,
address indexed player,
uint256 lotteryEnd,
uint256 amount
);
event StateChanged(uint256 indexed lotteryId, State oldState, State newState);
/**
* @notice Create a new lottery contract, sets the parameters informations
* and calls the `_initialize` function used to initialize a new lottery run.
* @param _name The name of the lottery
* @param _ticket The address of the corresponding ticket contract
* @param _token The address of the token used to play
* @param _cToken The address of the yield protocol token that earns interest
* @param _subscriptionId The subscription ID used for Chainlink VRF
* @param _vrfCoordinator The address of the VRF Coordinator
* @param _keyHash The key hash
*/
constructor(
string memory _name,
address _ticket,
address _token,
address _cToken,
uint64 _subscriptionId,
address _vrfCoordinator,
bytes32 _keyHash
)
CompoundYieldSourceInteractor(address(this))
VRFConsumerBaseV2(_vrfCoordinator)
{
name = _name;
ticket = Ticket(_ticket);
token = IERC20(_token);
cToken = ICToken(_cToken);
vrfCoordinator = VRFCoordinatorV2Interface(_vrfCoordinator);
subscriptionId = _subscriptionId;
keyHash = _keyHash;
_changeState(State.CLOSED);
_initialize();
}
/**
* @notice Function that creates a new lottery run and it transfers any
* reserve available into the yield protocol in order to enlarge the
* prize pool.
*/
function _initialize() internal {
uint256 reserve = token.balanceOf(address(this));
if (reserve > 0) {
require(
_supplyToCompound(address(token), address(cToken), reserve) == 0,
"PrizeLottery: SUPPLY_FAILED"
);
emit ReserveSupplied(lotteryId.current(), reserve);
}
latestLotteryTimestamp = block.timestamp;
lotteryId.increment();
_changeState(State.OPEN);
emit LotteryStarted(
lotteryId.current(),
latestLotteryTimestamp,
token,
cToken
);
}
/**
* @notice Allows the msg.sender to deposit tokens and join the lottery
* for the chance of winning. The amount of tokens deposited is transferred
* into a yield protocol and a corresponding number of tickets
* is minted for the msg.sender.
* @param _amount The amount of tokens deposited
* @return The ID of the user (msg.sender) and the amount of tickets he has
* on that moment
*/
function deposit(uint256 _amount) external returns (bytes32, uint256) {
require(State.OPEN == state, "PrizeLottery: REQUIRE_STATE_OPEN");
require(
_amount >= MINIMUM_DEPOSIT,
"PrizeLottery: INSUFFICIENT_DEPOSIT_AMOUNT"
);
IERC20(token).transferFrom(_msgSender(), address(this), _amount);
require(
_supplyToCompound(address(token), address(cToken), _amount) == 0,
"PrizeLottery: SUPPLY_FAILED"
);
ticket.controlledMint(_msgSender(), _amount);
emit PlayerDeposited(lotteryId.current(), _msgSender(), _amount);
return (
bytes32(uint256(uint160(_msgSender()))),
ticket.stakeOf(_msgSender())
);
}
/**
* @notice Allow the msg.sender to converts cTokens into a specified
* quantity of the underlying asset, and returns them to the msg.sender.
* An equal amount of tickets is also burned.
* @param _tokenAmount The amount of underlying to be redeemed
* @return The amount of tickets the caller has
*/
function redeem(uint256 _tokenAmount) external returns (uint256) {
require(
_tokenAmount <= ticket.stakeOf(_msgSender()),
"PrizeLottery: INSUFFICIENT_FUNDS_TO_REDEEM"
);
require(
_redeemUnderlyingFromCompound(address(cToken), _tokenAmount) == 0,
"PrizeLottery: REDEEM_FAILED"
);
ticket.controlledBurn(_msgSender(), _tokenAmount);
token.transfer(_msgSender(), _tokenAmount);
emit PlayerRedeemed(lotteryId.current(), _msgSender(), _tokenAmount);
return (ticket.stakeOf(_msgSender()));
}
/**
* @notice Function that, given a random generated number, picks an
* address and decrees it as the winner.
* @param _randomNumber The random number generated by the Chainlink VRF
*/
function _draw(uint256 _randomNumber) internal {
address pickedWinner = ticket.draw(_randomNumber);
require(isPickValid(pickedWinner), "PrizeLottery: PICK_NOT_VALID");
uint256 lotteryEnd = block.timestamp;
uint256 prize = prizePool();
ticket.controlledMint(pickedWinner, prize);
_changeState(State.CLOSED);
emit LotteryWinnerAwarded(
lotteryId.current(),
pickedWinner,
lotteryEnd,
prize
);
}
/**
* @notice This is the function that checks if the request of a random number
* can start.
* the following should be true for this to return true:
* 1. The time interval has passed between lottery runs
* 2. The lottery is open
* 3. The lottery is not empty
* @return True if the lottery is ready to draw, otherwise False
*/
function checkUpkeep() public view returns (bool) {
bool isOpen = State.OPEN == state;
bool timePassed = ((block.timestamp - latestLotteryTimestamp) >=
DRAWING_PERIOD);
return timePassed && isOpen && !isLotteryEmpty();
}
/**
* @notice Once `checkUpkeep` is returning `true`, this function is called,
* it starts the awarding winner process and kicks off a Chainlink VRF
* call to get a random winner.
*/
function performUpkeep() external {
require(checkUpkeep(), "PrizeLottery: UPKEEP_NOT_NEEDED");
_changeState(State.AWARDING_WINNER);
uint256 requestId = vrfCoordinator.requestRandomWords(
keyHash,
subscriptionId,
REQUEST_CONFIRMATIONS,
CALLBACK_GAS_LIMIT,
NUM_WORDS
);
emit RandomNumberRequested(lotteryId.current(), subscriptionId, requestId);
}
/**
* @notice Function that Chainlink VRF node calls when a random number is generated.
* @param randomWords Array containing `NUM_WORDS` random generated numbers
*/
function fulfillRandomWords(
uint256, /* requestId */
uint256[] memory randomWords
) internal override {
_changeState(State.RANDOMNESS_FULFILLED);
_draw(randomWords[0]);
_initialize();
}
/**
* @notice Utility function used to retrieve the current prize pool.
* @return The current prize pool
*/
function prizePool() public returns (uint256) {
uint256 depositedAmount = ticket.totalSupply();
uint256 totalAmount = _balanceOfUnderlyingCompound(address(cToken));
uint256 prize = (totalAmount < depositedAmount)
? type(uint256).min
: (totalAmount - depositedAmount);
return prize;
}
/**
* @notice Utility function that changes the lottery state.
* @param _state The new state
*/
function _changeState(State _state) internal {
if (_state == state) return;
State oldState = state;
state = _state;
emit StateChanged(lotteryId.current(), oldState, state);
}
/**
* @notice Utility function that allows the owner to change the lottery state.
* @param _state The new state
*/
function changeState(State _state) external onlyOwner {
if (_state == state) return;
State oldState = state;
state = _state;
emit StateChanged(lotteryId.current(), oldState, state);
}
/**
* @notice Utility function that checks if a certain address picked is valid.
* To be valid it needs to:
* 1. Not be the zero address
* 2. Be an address of a played that deposited and joined the lottery
* @param _playerPicked The address that needs to be checked
* @return True if the address is valid, otherwise False
*/
function isPickValid(address _playerPicked) public view returns (bool) {
if (
_playerPicked == address(0) ||
ticket.stakeOf(_playerPicked) == type(uint256).min
) return false;
return true;
}
/**
* @notice Utility function that checks if the lottery is empty or not.
* @return True if the lottery is empty, otherwise False
*/
function isLotteryEmpty() public view returns (bool) {
if (ticket.totalSupply() > 0) return false;
return true;
}
/**
* @notice The user's underlying balance, representing their
* assets in the protocol, is equal to the user's cToken balance
* multiplied by the Exchange Rate.
* @return The amount of underlying currently owned by this contract.
*/
function balanceOfUnderlyingCompound() public returns (uint256) {
return _balanceOfUnderlyingCompound(address(cToken));
}
/**
* @notice Get the current supply rate per block
* @return The current supply rate as an unsigned integer, scaled by 1e18.
*/
function supplyRatePerBlockCompound() public returns (uint256) {
return _supplyRatePerBlockCompound(address(cToken));
}
/**
* @notice Get the current exchange rate
* @return The current exchange rate as an unsigned integer,
* scaled by 1 * 10^(18 - 8 + Underlying Token Decimals)
*/
function exchangeRateCompound() public returns (uint256) {
return _exchangeRateCompound(address(cToken));
}
function getToken() public view returns (address) {
return address(token);
}
function getCtoken() public view returns (address) {
return address(cToken);
}
function getTicket() public view returns (address) {
return address(ticket);
}
}
| Utility function used to retrieve the current prize pool. return The current prize pool/ | function prizePool() public returns (uint256) {
uint256 depositedAmount = ticket.totalSupply();
uint256 totalAmount = _balanceOfUnderlyingCompound(address(cToken));
uint256 prize = (totalAmount < depositedAmount)
? type(uint256).min
: (totalAmount - depositedAmount);
return prize;
}
| 1,784,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.