file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
./full_match/1/0x92ffDD3334D6C8CE4906020C453037a71b3AA8f7/sources/contracts/interfaces/ICivFund.sol | Strategy Withdraw Address
| address[] withdrawAddress; | 16,543,365 | [
1,
4525,
3423,
9446,
5267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1758,
8526,
598,
9446,
1887,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
// 'Metadollar' CORE token contract
//
// Symbol : DOL
// Name : METADOLLAR
// Total supply: 1000,000,000,000
// Decimals : 18
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/issues/20
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
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 Owned{
address public owner;
address constant supervisor = 0x318B0f768f5c6c567227AA50B51B5b3078902f8C;
function owned(){
owner = msg.sender;
}
/// @notice Functions with this modifier can only be executed by the owner
modifier isOwner {
assert(msg.sender == owner || msg.sender == supervisor);
_;
}
/// @notice Transfer the ownership of this contract
function transferOwnership(address newOwner);
event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner);
}
contract METADOLLAR is ERC20Interface, Owned, SafeMath {
string public constant name = "METADOLLAR";
string public constant symbol = "DOL";
uint public constant decimals = 18;
uint256 public _totalSupply = 1000000000000000000000000000000;
uint256 public icoMin = 1000000000000000;
uint256 public preIcoLimit = 1000000000000000000;
uint256 public countHolders = 0; // count how many unique holders have tokens
uint256 public amountOfInvestments = 0; // amount of collected wei
uint256 public preICOprice;
uint256 public ICOprice;
uint256 preMtdRate = 1000;
uint256 mtdRate = 1000;
uint256 sellRate = 900;
uint256 commissionRate = 900;
uint256 public sellPrice;
uint256 public currentTokenPrice;
uint256 public commission;
bool public preIcoIsRunning;
bool public minimalGoalReached;
bool public icoIsClosed;
//Balances for each account
mapping (address => uint256) public tokenBalanceOf;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
//list with information about frozen accounts
mapping(address => bool) frozenAccount;
//this generate a public event on a blockchain that will notify clients
event FrozenFunds(address initiator, address account, string status);
//this generate a public event on a blockchain that will notify clients
event BonusChanged(uint8 bonusOld, uint8 bonusNew);
//this generate a public event on a blockchain that will notify clients
event minGoalReached(uint256 minIcoAmount, string notice);
//this generate a public event on a blockchain that will notify clients
event preIcoEnded(uint256 preIcoAmount, string notice);
//this generate a public event on a blockchain that will notify clients
event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice);
//this generate a public event on a blockchain that will notify clients
event withdrawed(address _to, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event deposited(address _from, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event tokenCreated(address _creator, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event tokenDestroyed(address _destroyer, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event icoStatusUpdated(address _initiator, string status);
/// @notice Constructor of the contract
function STARTMETADOLLAR() {
preIcoIsRunning = true;
minimalGoalReached = false;
icoIsClosed = false;
tokenBalanceOf[this] += _totalSupply;
allowed[this][owner] = _totalSupply;
allowed[this][supervisor] = _totalSupply;
currentTokenPrice = 1 * 1; // initial price of 1 Token
preICOprice = (msg.value) * preMtdRate;
ICOprice = (msg.value) * mtdRate;
sellPrice = (msg.value) * sellRate;
updatePrices();
}
function () payable {
require(!frozenAccount[msg.sender]);
if(msg.value > 0 && !frozenAccount[msg.sender]) {
buyToken();
}
}
/// @notice Returns a whole amount of tokens
function totalSupply() constant returns (uint256 totalAmount) {
totalAmount = _totalSupply;
}
/// @notice What is the balance of a particular account?
function balanceOf(address _owner) constant returns (uint256 balance) {
return tokenBalanceOf[_owner];
}
/// @notice Shows how much tokens _spender can spend from _owner address
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice Calculates amount of weis needed to buy more than one token
/// @param howManyTokenToBuy - Amount of tokens to calculate
function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) {
if(howManyTokenToBuy > 0) {
summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice;
}else {
summarizedPriceInWeis = 0;
}
}
/// @notice Shows if account is frozen
/// @param account - Accountaddress to check
function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) {
accountIsFrozen = frozenAccount[account];
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
require(!frozenAccount[msg.sender]);
require(msg.value > 0);
buyToken();
}
/// @notice Sell tokens and receive ether from contract
function sell(uint256 amount) {
require(!frozenAccount[msg.sender]);
require(tokenBalanceOf[msg.sender] >= amount); // checks if the sender has enough to sell
require(amount > 0);
require(sellPrice > 0);
_transfer(msg.sender, this, amount);
uint256 revenue = amount * sellPrice;
require(this.balance >= revenue);
commission = msg.value/commissionRate; // % of wei tx
require(address(this).send(commission));
msg.sender.transfer(revenue); // sends ether to the seller: it's important to do this last to prevent recursion attacks
}
function sell2(address _tokenAddress) public payable{
METADOLLAR token = METADOLLAR(_tokenAddress);
uint tokens = msg.value * sellPrice;
require(token.balanceOf(this) >= tokens);
commission = msg.value/commissionRate; // % of wei tx
require(address(this).send(commission));
token.transfer(msg.sender, tokens);
}
/// @notice Transfer amount of tokens from own wallet to someone else
function transfer(address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[msg.sender] >= _value);
require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
_transfer(msg.sender, _to, _value);
return true;
}
/// @notice Send _value amount of tokens from address _from to address _to
/// @notice The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// @notice tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// @notice fees in sub-currencies; the command should fail unless the _from account has
/// @notice deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_from != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer tokens from allowed account");
_transfer(_from, _to, _value);
allowed[_from][msg.sender] -= _value;
return true;
}
/// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// @notice If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
assert(_spender != address(0));
require(_value >= 0);
allowed[msg.sender][_spender] = _value;
return true;
}
/// @notice Check if minimal goal of ICO is reached
function checkMinimalGoal() internal {
if(tokenBalanceOf[this] <= _totalSupply - icoMin) {
minimalGoalReached = true;
minGoalReached(icoMin, "Minimal goal of ICO is reached!");
}
}
/// @notice Check if preICO is ended
function checkPreIcoStatus() internal {
if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) {
preIcoIsRunning = false;
preIcoEnded(preIcoLimit, "Token amount for preICO sold!");
}
}
/// @notice Processing each buying
function buyToken() internal {
uint256 value = msg.value;
address sender = msg.sender;
require(!icoIsClosed);
require(!frozenAccount[sender]);
require(value > 0);
require(currentTokenPrice > 0);
uint256 amount = value / currentTokenPrice; // calculates amount of tokens
uint256 moneyBack = value - (amount * sellPrice);
require(tokenBalanceOf[this] >= amount); // checks if contract has enough to sell
amountOfInvestments = amountOfInvestments + (value - moneyBack);
updatePrices();
_transfer(this, sender, amount);
if(moneyBack > 0) {
sender.transfer(moneyBack);
}
}
/// @notice Internal transfer, can only be called by this contract
function _transfer(address _from, address _to, uint256 _value) internal {
assert(_from != address(0));
assert(_to != address(0));
require(_value > 0);
require(tokenBalanceOf[_from] >= _value);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if(tokenBalanceOf[_to] == 0){
countHolders += 1;
}
tokenBalanceOf[_from] -= _value;
if(tokenBalanceOf[_from] == 0){
countHolders -= 1;
}
tokenBalanceOf[_to] += _value;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
Transfer(_from, _to, _value);
}
/// @notice Set current ICO prices in wei for one token
function updatePrices() internal {
uint256 oldPrice = currentTokenPrice;
if(preIcoIsRunning) {
checkPreIcoStatus();
}
if(preIcoIsRunning) {
currentTokenPrice = preICOprice;
}else{
currentTokenPrice = ICOprice;
}
if(oldPrice != currentTokenPrice) {
priceUpdated(oldPrice, currentTokenPrice, "Token price updated!");
}
}
/// @notice Set current preICO price in wei for one token
/// @param priceForPreIcoInWei - is the amount in wei for one token
function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(preICOprice != priceForPreIcoInWei);
preICOprice = priceForPreIcoInWei;
updatePrices();
}
/// @notice Set current ICO price in wei for one token
/// @param priceForIcoInWei - is the amount in wei for one token
function setICOPrice(uint256 priceForIcoInWei) isOwner {
require(priceForIcoInWei > 0);
require(ICOprice != priceForIcoInWei);
ICOprice = priceForIcoInWei;
updatePrices();
}
/// @notice Set both prices at the same time
/// @param priceForPreIcoInWei - Price of the token in pre ICO
/// @param priceForIcoInWei - Price of the token in ICO
function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(priceForIcoInWei > 0);
preICOprice = priceForPreIcoInWei;
ICOprice = priceForIcoInWei;
updatePrices();
}
/// @notice Set the current sell price in wei for one token
/// @param priceInWei - is the amount in wei for one token
function setSellPrice(uint256 priceInWei) isOwner {
require(priceInWei >= 0);
sellPrice = priceInWei;
}
/// @notice Set the current commission rate
/// @param commissionRateInWei - commission rate
function setCommissionRate(uint256 commissionRateInWei) isOwner {
require(commissionRateInWei >= 0);
commissionRate = commissionRateInWei;
}
/// @notice 'freeze? Prevent | Allow' 'account' from sending and receiving tokens
/// @param account - address to be frozen
/// @param freeze - select is the account frozen or not
function freezeAccount(address account, bool freeze) isOwner {
require(account != owner);
require(account != supervisor);
frozenAccount[account] = freeze;
if(freeze) {
FrozenFunds(msg.sender, account, "Account set frozen!");
}else {
FrozenFunds(msg.sender, account, "Account set free for use!");
}
}
/// @notice Create an amount of token
/// @param amount - token to create
function mintToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] <= icoMin); // owner can create token only if the initial amount is strongly not enough to supply and demand ICO
require(_totalSupply + amount > _totalSupply);
require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]);
_totalSupply += amount;
tokenBalanceOf[this] += amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenCreated(msg.sender, amount, "Additional tokens created!");
}
/// @notice Destroy an amount of token
/// @param amount - token to destroy
function destroyToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] >= amount);
require(_totalSupply >= amount);
require(tokenBalanceOf[this] - amount >= 0);
require(_totalSupply - amount >= 0);
tokenBalanceOf[this] -= amount;
_totalSupply -= amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!");
}
/// @notice Transfer the ownership to another account
/// @param newOwner - address who get the ownership
function transferOwnership(address newOwner) isOwner {
assert(newOwner != address(0));
address oldOwner = owner;
owner = newOwner;
ownerChanged(msg.sender, oldOwner, newOwner);
allowed[this][oldOwner] = 0;
allowed[this][newOwner] = tokenBalanceOf[this];
}
/// @notice Transfer all ether from smartcontract to owner
function collect() isOwner {
require(this.balance > 0);
withdraw(this.balance);
}
/// @notice Withdraw an amount of ether
/// @param summeInWei - amout to withdraw
function withdraw(uint256 summeInWei) isOwner {
uint256 contractbalance = this.balance;
address sender = msg.sender;
require(contractbalance >= summeInWei);
withdrawed(sender, summeInWei, "wei withdrawed");
sender.transfer(summeInWei);
}
/// @notice Deposit an amount of ether
function deposit() payable isOwner {
require(msg.value > 0);
require(msg.sender.balance >= msg.value);
deposited(msg.sender, msg.value, "wei deposited");
}
/// @notice Stop running ICO
/// @param icoIsStopped - status if this ICO is stopped
function stopThisIco(bool icoIsStopped) isOwner {
require(icoIsClosed != icoIsStopped);
icoIsClosed = icoIsStopped;
if(icoIsStopped) {
icoStatusUpdated(msg.sender, "Coin offering was stopped!");
}else {
icoStatusUpdated(msg.sender, "Coin offering is running!");
}
}
} | @notice Transfer the ownership of this contractBalances for each account Owner of account approves the transfer of an amount to another accountlist with information about frozen accountsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clients | contract METADOLLAR is ERC20Interface, Owned, SafeMath {
string public constant name = "METADOLLAR";
string public constant symbol = "DOL";
uint public constant decimals = 18;
uint256 public _totalSupply = 1000000000000000000000000000000;
uint256 public icoMin = 1000000000000000;
uint256 public preIcoLimit = 1000000000000000000;
uint256 public preICOprice;
uint256 public ICOprice;
uint256 preMtdRate = 1000;
uint256 mtdRate = 1000;
uint256 sellRate = 900;
uint256 commissionRate = 900;
uint256 public sellPrice;
uint256 public currentTokenPrice;
uint256 public commission;
bool public preIcoIsRunning;
bool public minimalGoalReached;
bool public icoIsClosed;
mapping (address => uint256) public tokenBalanceOf;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => bool) frozenAccount;
event FrozenFunds(address initiator, address account, string status);
event BonusChanged(uint8 bonusOld, uint8 bonusNew);
event minGoalReached(uint256 minIcoAmount, string notice);
event preIcoEnded(uint256 preIcoAmount, string notice);
event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice);
event withdrawed(address _to, uint256 summe, string notice);
event deposited(address _from, uint256 summe, string notice);
event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice);
event tokenCreated(address _creator, uint256 summe, string notice);
event tokenDestroyed(address _destroyer, uint256 summe, string notice);
event icoStatusUpdated(address _initiator, string status);
function transferOwnership(address newOwner);
event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner);
}
function STARTMETADOLLAR() {
preIcoIsRunning = true;
minimalGoalReached = false;
icoIsClosed = false;
tokenBalanceOf[this] += _totalSupply;
allowed[this][owner] = _totalSupply;
allowed[this][supervisor] = _totalSupply;
preICOprice = (msg.value) * preMtdRate;
ICOprice = (msg.value) * mtdRate;
sellPrice = (msg.value) * sellRate;
updatePrices();
}
function () payable {
require(!frozenAccount[msg.sender]);
if(msg.value > 0 && !frozenAccount[msg.sender]) {
buyToken();
}
}
function () payable {
require(!frozenAccount[msg.sender]);
if(msg.value > 0 && !frozenAccount[msg.sender]) {
buyToken();
}
}
function totalSupply() constant returns (uint256 totalAmount) {
totalAmount = _totalSupply;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return tokenBalanceOf[_owner];
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) {
if(howManyTokenToBuy > 0) {
summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice;
summarizedPriceInWeis = 0;
}
}
function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) {
if(howManyTokenToBuy > 0) {
summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice;
summarizedPriceInWeis = 0;
}
}
}else {
function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) {
accountIsFrozen = frozenAccount[account];
}
function buy() payable public {
require(!frozenAccount[msg.sender]);
require(msg.value > 0);
buyToken();
}
function sell(uint256 amount) {
require(!frozenAccount[msg.sender]);
require(amount > 0);
require(sellPrice > 0);
_transfer(msg.sender, this, amount);
uint256 revenue = amount * sellPrice;
require(this.balance >= revenue);
require(address(this).send(commission));
}
function sell2(address _tokenAddress) public payable{
METADOLLAR token = METADOLLAR(_tokenAddress);
uint tokens = msg.value * sellPrice;
require(token.balanceOf(this) >= tokens);
require(address(this).send(commission));
token.transfer(msg.sender, tokens);
}
function transfer(address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[msg.sender] >= _value);
require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_from != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer tokens from allowed account");
_transfer(_from, _to, _value);
allowed[_from][msg.sender] -= _value;
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
assert(_spender != address(0));
require(_value >= 0);
allowed[msg.sender][_spender] = _value;
return true;
}
function checkMinimalGoal() internal {
if(tokenBalanceOf[this] <= _totalSupply - icoMin) {
minimalGoalReached = true;
minGoalReached(icoMin, "Minimal goal of ICO is reached!");
}
}
function checkMinimalGoal() internal {
if(tokenBalanceOf[this] <= _totalSupply - icoMin) {
minimalGoalReached = true;
minGoalReached(icoMin, "Minimal goal of ICO is reached!");
}
}
function checkPreIcoStatus() internal {
if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) {
preIcoIsRunning = false;
preIcoEnded(preIcoLimit, "Token amount for preICO sold!");
}
}
function checkPreIcoStatus() internal {
if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) {
preIcoIsRunning = false;
preIcoEnded(preIcoLimit, "Token amount for preICO sold!");
}
}
function buyToken() internal {
uint256 value = msg.value;
address sender = msg.sender;
require(!icoIsClosed);
require(!frozenAccount[sender]);
require(value > 0);
require(currentTokenPrice > 0);
uint256 moneyBack = value - (amount * sellPrice);
amountOfInvestments = amountOfInvestments + (value - moneyBack);
updatePrices();
_transfer(this, sender, amount);
if(moneyBack > 0) {
sender.transfer(moneyBack);
}
}
function buyToken() internal {
uint256 value = msg.value;
address sender = msg.sender;
require(!icoIsClosed);
require(!frozenAccount[sender]);
require(value > 0);
require(currentTokenPrice > 0);
uint256 moneyBack = value - (amount * sellPrice);
amountOfInvestments = amountOfInvestments + (value - moneyBack);
updatePrices();
_transfer(this, sender, amount);
if(moneyBack > 0) {
sender.transfer(moneyBack);
}
}
function _transfer(address _from, address _to, uint256 _value) internal {
assert(_from != address(0));
assert(_to != address(0));
require(_value > 0);
require(tokenBalanceOf[_from] >= _value);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if(tokenBalanceOf[_to] == 0){
countHolders += 1;
}
tokenBalanceOf[_from] -= _value;
if(tokenBalanceOf[_from] == 0){
countHolders -= 1;
}
tokenBalanceOf[_to] += _value;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
Transfer(_from, _to, _value);
}
function _transfer(address _from, address _to, uint256 _value) internal {
assert(_from != address(0));
assert(_to != address(0));
require(_value > 0);
require(tokenBalanceOf[_from] >= _value);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if(tokenBalanceOf[_to] == 0){
countHolders += 1;
}
tokenBalanceOf[_from] -= _value;
if(tokenBalanceOf[_from] == 0){
countHolders -= 1;
}
tokenBalanceOf[_to] += _value;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
Transfer(_from, _to, _value);
}
function _transfer(address _from, address _to, uint256 _value) internal {
assert(_from != address(0));
assert(_to != address(0));
require(_value > 0);
require(tokenBalanceOf[_from] >= _value);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if(tokenBalanceOf[_to] == 0){
countHolders += 1;
}
tokenBalanceOf[_from] -= _value;
if(tokenBalanceOf[_from] == 0){
countHolders -= 1;
}
tokenBalanceOf[_to] += _value;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
Transfer(_from, _to, _value);
}
function updatePrices() internal {
uint256 oldPrice = currentTokenPrice;
if(preIcoIsRunning) {
checkPreIcoStatus();
}
if(preIcoIsRunning) {
currentTokenPrice = preICOprice;
currentTokenPrice = ICOprice;
}
if(oldPrice != currentTokenPrice) {
priceUpdated(oldPrice, currentTokenPrice, "Token price updated!");
}
}
function updatePrices() internal {
uint256 oldPrice = currentTokenPrice;
if(preIcoIsRunning) {
checkPreIcoStatus();
}
if(preIcoIsRunning) {
currentTokenPrice = preICOprice;
currentTokenPrice = ICOprice;
}
if(oldPrice != currentTokenPrice) {
priceUpdated(oldPrice, currentTokenPrice, "Token price updated!");
}
}
function updatePrices() internal {
uint256 oldPrice = currentTokenPrice;
if(preIcoIsRunning) {
checkPreIcoStatus();
}
if(preIcoIsRunning) {
currentTokenPrice = preICOprice;
currentTokenPrice = ICOprice;
}
if(oldPrice != currentTokenPrice) {
priceUpdated(oldPrice, currentTokenPrice, "Token price updated!");
}
}
}else{
function updatePrices() internal {
uint256 oldPrice = currentTokenPrice;
if(preIcoIsRunning) {
checkPreIcoStatus();
}
if(preIcoIsRunning) {
currentTokenPrice = preICOprice;
currentTokenPrice = ICOprice;
}
if(oldPrice != currentTokenPrice) {
priceUpdated(oldPrice, currentTokenPrice, "Token price updated!");
}
}
function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(preICOprice != priceForPreIcoInWei);
preICOprice = priceForPreIcoInWei;
updatePrices();
}
function setICOPrice(uint256 priceForIcoInWei) isOwner {
require(priceForIcoInWei > 0);
require(ICOprice != priceForIcoInWei);
ICOprice = priceForIcoInWei;
updatePrices();
}
function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(priceForIcoInWei > 0);
preICOprice = priceForPreIcoInWei;
ICOprice = priceForIcoInWei;
updatePrices();
}
function setSellPrice(uint256 priceInWei) isOwner {
require(priceInWei >= 0);
sellPrice = priceInWei;
}
function setCommissionRate(uint256 commissionRateInWei) isOwner {
require(commissionRateInWei >= 0);
commissionRate = commissionRateInWei;
}
function freezeAccount(address account, bool freeze) isOwner {
require(account != owner);
require(account != supervisor);
frozenAccount[account] = freeze;
if(freeze) {
FrozenFunds(msg.sender, account, "Account set frozen!");
FrozenFunds(msg.sender, account, "Account set free for use!");
}
}
function freezeAccount(address account, bool freeze) isOwner {
require(account != owner);
require(account != supervisor);
frozenAccount[account] = freeze;
if(freeze) {
FrozenFunds(msg.sender, account, "Account set frozen!");
FrozenFunds(msg.sender, account, "Account set free for use!");
}
}
}else {
function mintToken(uint256 amount) isOwner {
require(amount > 0);
require(_totalSupply + amount > _totalSupply);
require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]);
_totalSupply += amount;
tokenBalanceOf[this] += amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenCreated(msg.sender, amount, "Additional tokens created!");
}
function destroyToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] >= amount);
require(_totalSupply >= amount);
require(tokenBalanceOf[this] - amount >= 0);
require(_totalSupply - amount >= 0);
tokenBalanceOf[this] -= amount;
_totalSupply -= amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!");
}
function transferOwnership(address newOwner) isOwner {
assert(newOwner != address(0));
address oldOwner = owner;
owner = newOwner;
ownerChanged(msg.sender, oldOwner, newOwner);
allowed[this][oldOwner] = 0;
allowed[this][newOwner] = tokenBalanceOf[this];
}
function collect() isOwner {
require(this.balance > 0);
withdraw(this.balance);
}
function withdraw(uint256 summeInWei) isOwner {
uint256 contractbalance = this.balance;
address sender = msg.sender;
require(contractbalance >= summeInWei);
withdrawed(sender, summeInWei, "wei withdrawed");
sender.transfer(summeInWei);
}
function deposit() payable isOwner {
require(msg.value > 0);
require(msg.sender.balance >= msg.value);
deposited(msg.sender, msg.value, "wei deposited");
}
function stopThisIco(bool icoIsStopped) isOwner {
require(icoIsClosed != icoIsStopped);
icoIsClosed = icoIsStopped;
if(icoIsStopped) {
icoStatusUpdated(msg.sender, "Coin offering was stopped!");
icoStatusUpdated(msg.sender, "Coin offering is running!");
}
}
function stopThisIco(bool icoIsStopped) isOwner {
require(icoIsClosed != icoIsStopped);
icoIsClosed = icoIsStopped;
if(icoIsStopped) {
icoStatusUpdated(msg.sender, "Coin offering was stopped!");
icoStatusUpdated(msg.sender, "Coin offering is running!");
}
}
}else {
} | 7,753,353 | [
1,
5912,
326,
23178,
434,
333,
6835,
38,
26488,
364,
1517,
2236,
16837,
434,
2236,
6617,
3324,
326,
7412,
434,
392,
3844,
358,
4042,
2236,
1098,
598,
1779,
2973,
12810,
2236,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
291,
2103,
279,
1071,
871,
603,
279,
16766,
716,
903,
5066,
1004,
20244,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
6791,
1880,
30922,
985,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
377,
203,
377,
203,
203,
202,
1080,
1071,
5381,
508,
273,
315,
18315,
1880,
30922,
985,
14432,
203,
202,
1080,
1071,
5381,
3273,
273,
315,
40,
1741,
14432,
203,
202,
11890,
1071,
5381,
15105,
273,
6549,
31,
203,
202,
11890,
5034,
1071,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
12648,
2787,
31,
203,
202,
11890,
5034,
1071,
277,
2894,
2930,
273,
2130,
12648,
11706,
31,
25083,
203,
202,
11890,
5034,
1071,
675,
45,
2894,
3039,
273,
2130,
12648,
12648,
31,
9506,
203,
202,
203,
202,
11890,
5034,
1071,
675,
2871,
3817,
3057,
31,
203,
202,
11890,
5034,
1071,
26899,
3817,
3057,
31,
202,
203,
565,
2254,
5034,
675,
49,
4465,
4727,
273,
4336,
31,
203,
202,
11890,
5034,
312,
4465,
4727,
273,
4336,
31,
203,
202,
11890,
5034,
357,
80,
4727,
273,
2468,
713,
31,
203,
202,
11890,
5034,
1543,
19710,
4727,
273,
2468,
713,
31,
203,
202,
11890,
5034,
1071,
357,
80,
5147,
31,
203,
202,
11890,
5034,
1071,
23719,
5147,
31,
6862,
203,
202,
11890,
5034,
1071,
1543,
19710,
31,
202,
203,
202,
203,
202,
203,
202,
6430,
1071,
675,
45,
2894,
2520,
7051,
31,
203,
202,
6430,
1071,
16745,
27716,
23646,
31,
203,
202,
6430,
1071,
277,
2894,
2520,
7395,
31,
203,
202,
203,
203,
202,
6770,
261,
2867,
516,
2254,
5034,
13,
1071,
1147,
13937,
951,
31,
203,
203,
202,
6770,
12,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2
] |
./full_match/4/0x16EFC807B4DAB998Ade18b5FC899f193FBD8Cb47/sources/ElevenElevenTest.sol | 200 - 299 0.25 ETH
| return [uint256(250000000000000000),0]; | 13,299,569 | [
1,
6976,
300,
31360,
374,
18,
2947,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
327,
306,
11890,
5034,
12,
2947,
12648,
12648,
3631,
20,
15533,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
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
);
}
library SafeMath {
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;
}
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;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ConnectCandy is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor() public {
_name = "Connect Candy";
_symbol = "CC";
_decimals = 18;
_totalSupply = 5000 * 100000000 * 10 ** 18;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
/**
* @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;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
} | * @return the number of decimals of the token./ | function decimals() public view returns(uint8) {
return _decimals;
}
| 6,333,930 | [
1,
2463,
326,
1300,
434,
15105,
434,
326,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
15105,
1435,
1071,
1476,
1135,
12,
11890,
28,
13,
288,
203,
565,
327,
389,
31734,
31,
203,
225,
289,
203,
21281,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.15;
//import './lib/safeMath.sol';
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// import './ERC20.sol';
contract ERC20 {
uint256 public totalSupply;
function transferFrom(address from, address to, uint256 value) returns (bool);
function transfer(address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
function allowance(address owner, address spender) constant returns (uint256);
function balanceOf(address who) constant returns (uint256);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// import './helpers/BasicToken.sol';
contract BasicToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
uint256 _allowance = allowed[_from][msg.sender];
allowed[_from][msg.sender] = _allowance.sub(_value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
Transfer(_from, _to, _value);
return true;
}
return false;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// import './BiQToken.sol';
contract BiQToken is BasicToken {
using SafeMath for uint256;
string public name = "BurstIQ Token"; //name of the token
string public symbol = "BiQ"; // symbol of the token
uint8 public decimals = 18; // decimals
uint256 public totalSupply = 1000000000 * 10**18; // total supply of BiQ Tokens
// variables
uint256 public keyEmployeesAllocatedFund; // fund allocated to key employees
uint256 public advisorsAllocation; // fund allocated to advisors
uint256 public marketIncentivesAllocation; // fund allocated to Market
uint256 public vestingFounderAllocation; // funds allocated to founders that in under vesting period
uint256 public totalAllocatedTokens; // variable to keep track of funds allocated
uint256 public tokensAllocatedToCrowdFund; // funds allocated to crowdfund
uint256 public saftInvestorAllocation; // funds allocated to private presales and instituational investors
bool public isPublicTokenReleased = false; // flag to track the release the public token
// addresses
address public founderMultiSigAddress; // multi sign address of founders which hold
address public advisorAddress; // advisor address which hold advisorsAllocation funds
address public vestingFounderAddress; // address of founder that hold vestingFounderAllocation
address public crowdFundAddress; // address of crowdfund contract
// vesting period
uint256 public preAllocatedTokensVestingTime; // crowdfund start time + 6 months
//events
event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress);
event TransferPreAllocatedFunds(uint256 _blockTimeStamp , address _to , uint256 _value);
event PublicTokenReleased(uint256 _blockTimeStamp);
//modifiers
modifier onlyCrowdFundAddress() {
require(msg.sender == crowdFundAddress);
_;
}
modifier nonZeroAddress(address _to) {
require(_to != 0x0);
_;
}
modifier onlyFounders() {
require(msg.sender == founderMultiSigAddress);
_;
}
modifier onlyVestingFounderAddress() {
require(msg.sender == vestingFounderAddress);
_;
}
modifier onlyAdvisorAddress() {
require(msg.sender == advisorAddress);
_;
}
modifier isPublicTokenNotReleased() {
require(isPublicTokenReleased == false);
_;
}
// creation of the token contract
function BiQToken (address _crowdFundAddress, address _founderMultiSigAddress, address _advisorAddress, address _vestingFounderAddress) {
crowdFundAddress = _crowdFundAddress;
founderMultiSigAddress = _founderMultiSigAddress;
vestingFounderAddress = _vestingFounderAddress;
advisorAddress = _advisorAddress;
// Token Distribution
vestingFounderAllocation = 18 * 10 ** 25 ; // 18 % allocation of totalSupply
keyEmployeesAllocatedFund = 2 * 10 ** 25 ; // 2 % allocation of totalSupply
advisorsAllocation = 5 * 10 ** 25 ; // 5 % allocation of totalSupply
tokensAllocatedToCrowdFund = 60 * 10 ** 25 ; // 60 % allocation of totalSupply
marketIncentivesAllocation = 5 * 10 ** 25 ; // 5 % allocation of totalSupply
saftInvestorAllocation = 10 * 10 ** 25 ; // 10 % alloaction of totalSupply
// Assigned balances to respective stakeholders
balances[founderMultiSigAddress] = keyEmployeesAllocatedFund + saftInvestorAllocation;
balances[crowdFundAddress] = tokensAllocatedToCrowdFund;
totalAllocatedTokens = balances[founderMultiSigAddress];
preAllocatedTokensVestingTime = now + 180 * 1 days; // it should be 6 months period for vesting
}
// function to keep track of the total token allocation
function changeTotalSupply(uint256 _amount) onlyCrowdFundAddress {
totalAllocatedTokens = totalAllocatedTokens.add(_amount);
tokensAllocatedToCrowdFund = tokensAllocatedToCrowdFund.sub(_amount);
}
// function to change founder multisig wallet address
function changeFounderMultiSigAddress(address _newFounderMultiSigAddress) onlyFounders nonZeroAddress(_newFounderMultiSigAddress) {
founderMultiSigAddress = _newFounderMultiSigAddress;
ChangeFoundersWalletAddress(now, founderMultiSigAddress);
}
// function for releasing the public tokens called once by the founder only
function releaseToken() onlyFounders isPublicTokenNotReleased {
isPublicTokenReleased = !isPublicTokenReleased;
PublicTokenReleased(now);
}
// function to transfer market Incentives fund
function transferMarketIncentivesFund(address _to, uint _value) onlyFounders nonZeroAddress(_to) returns (bool) {
if (marketIncentivesAllocation >= _value) {
marketIncentivesAllocation = marketIncentivesAllocation.sub(_value);
balances[_to] = balances[_to].add(_value);
totalAllocatedTokens = totalAllocatedTokens.add(_value);
TransferPreAllocatedFunds(now, _to, _value);
return true;
}
return false;
}
// fund transferred to vesting Founders address after 6 months
function getVestedFounderTokens() onlyVestingFounderAddress returns (bool) {
if (now >= preAllocatedTokensVestingTime && vestingFounderAllocation > 0) {
balances[vestingFounderAddress] = balances[vestingFounderAddress].add(vestingFounderAllocation);
totalAllocatedTokens = totalAllocatedTokens.add(vestingFounderAllocation);
vestingFounderAllocation = 0;
TransferPreAllocatedFunds(now, vestingFounderAddress, vestingFounderAllocation);
return true;
}
return false;
}
// fund transferred to vesting advisor address after 6 months
function getVestedAdvisorTokens() onlyAdvisorAddress returns (bool) {
if (now >= preAllocatedTokensVestingTime && advisorsAllocation > 0) {
balances[advisorAddress] = balances[advisorAddress].add(advisorsAllocation);
totalAllocatedTokens = totalAllocatedTokens.add(advisorsAllocation);
advisorsAllocation = 0;
TransferPreAllocatedFunds(now, advisorAddress, advisorsAllocation);
return true;
} else {
return false;
}
}
// overloaded transfer function to restrict the investor to transfer the token before the ICO sale ends
function transfer(address _to, uint256 _value) returns (bool) {
if (msg.sender == crowdFundAddress) {
return super.transfer(_to,_value);
} else {
if (isPublicTokenReleased) {
return super.transfer(_to,_value);
}
return false;
}
}
// overloaded transferFrom function to restrict the investor to transfer the token before the ICO sale ends
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
if (msg.sender == crowdFundAddress) {
return super.transferFrom(_from, _to, _value);
} else {
if (isPublicTokenReleased) {
return super.transferFrom(_from, _to, _value);
}
return false;
}
}
// fallback function to restrict direct sending of ether
function () {
revert();
}
}
contract BiQCrowdFund {
using SafeMath for uint256;
BiQToken public token; // Token contract reference
//variables
uint256 public crowdfundStartTime; // Starting time of CrowdFund
uint256 public crowdfundEndTime; // End time of Crowdfund
uint256 public totalWeiRaised = 0; // Counter to track the amount raised
uint256 public exchangeRate = 2307; // Calculated using priceOfEtherInUSD/priceOfBiQToken so 276.84/0.12
uint256 internal minAmount = 36.1219 * 10 ** 18; // Calculated using 10k USD / 276.84 USD
bool public isCrowdFundActive = false; // Flag to track the crowdfund active or not
bool internal isTokenDeployed = false; // Flag to track the token deployment -- only can be set once
bool internal hasCrowdFundStarted = false; // Flag to track if the crowdfund started
// addresses
address public founderMultiSigAddress; // Founders multisig address
address public remainingTokenHolder; // Address to hold the remaining tokens after crowdfund end
address public authorizerAddress; // Address of Authorizer who will authorize the investor
// mapping
mapping (address => uint256) auth; // KYC authentication
enum State { PreSale, CrowdFund }
//events
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event CrowdFundClosed(uint256 _blockTimeStamp);
event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress);
//Modifiers
modifier tokenIsDeployed() {
require(isTokenDeployed == true);
_;
}
modifier nonZeroEth() {
require(msg.value > 0);
_;
}
modifier nonZeroAddress(address _to) {
require(_to != 0x0);
_;
}
modifier checkCrowdFundActive() {
require(isCrowdFundActive == true);
_;
}
modifier onlyFounders() {
require(msg.sender == founderMultiSigAddress);
_;
}
modifier onlyPublic() {
require(msg.sender != founderMultiSigAddress);
_;
}
modifier onlyAuthorizer() {
require(msg.sender == authorizerAddress);
_;
}
modifier inState(State state) {
require(getState() == state);
_;
}
// Constructor to initialize the local variables
function BiQCrowdFund (address _founderWalletAddress, address _remainingTokenHolder, address _authorizerAddress) {
founderMultiSigAddress = _founderWalletAddress;
remainingTokenHolder = _remainingTokenHolder;
authorizerAddress = _authorizerAddress;
}
// Function to change the founders multisig address
function setFounderMultiSigAddress(address _newFounderAddress) onlyFounders nonZeroAddress(_newFounderAddress) {
founderMultiSigAddress = _newFounderAddress;
ChangeFoundersWalletAddress(now, founderMultiSigAddress);
}
function setAuthorizerAddress(address _newAuthorizerAddress) onlyFounders nonZeroAddress(_newAuthorizerAddress) {
authorizerAddress = _newAuthorizerAddress;
}
function setRemainingTokenHolder(address _newRemainingTokenHolder) onlyFounders nonZeroAddress(_newRemainingTokenHolder) {
remainingTokenHolder = _newRemainingTokenHolder;
}
// Attach the token contract, can only be done once
function setTokenAddress(address _tokenAddress) onlyFounders nonZeroAddress(_tokenAddress) {
require(isTokenDeployed == false);
token = BiQToken(_tokenAddress);
isTokenDeployed = true;
}
// change the state of crowdfund
function changeCrowdfundState() tokenIsDeployed onlyFounders inState(State.CrowdFund) {
isCrowdFundActive = !isCrowdFundActive;
}
// for KYC/AML
function authorize(address _to, uint256 max_amount) onlyAuthorizer {
auth[_to] = max_amount * 1 ether;
}
// Buy token function call only in duration of crowdfund active
function buyTokens(address beneficiary) nonZeroEth tokenIsDeployed onlyPublic nonZeroAddress(beneficiary) payable returns(bool) {
// Only allow a certain amount for every investor
if (auth[beneficiary] < msg.value) {
revert();
}
auth[beneficiary] = auth[beneficiary].sub(msg.value);
if (getState() == State.PreSale) {
if (buyPreSaleTokens(beneficiary)) {
return true;
}
revert();
} else {
require(now < crowdfundEndTime && isCrowdFundActive);
fundTransfer(msg.value);
uint256 amount = getNoOfTokens(exchangeRate, msg.value);
if (token.transfer(beneficiary, amount)) {
token.changeTotalSupply(amount);
totalWeiRaised = totalWeiRaised.add(msg.value);
TokenPurchase(beneficiary, msg.value, amount);
return true;
}
revert();
}
}
// function to transfer the funds to founders account
function fundTransfer(uint256 weiAmount) internal {
founderMultiSigAddress.transfer(weiAmount);
}
///////////////////////////////////// Constant Functions /////////////////////////////////////
// function to get the current state of the crowdsale
function getState() public constant returns(State) {
if (!isCrowdFundActive && !hasCrowdFundStarted) {
return State.PreSale;
}
return State.CrowdFund;
}
// To get the authorized amount corresponding to an address
function getPreAuthorizedAmount(address _address) constant returns(uint256) {
return auth[_address];
}
// get the amount of tokens a user would receive for a specific amount of ether
function calculateTotalTokenPerContribution(uint256 _totalETHContribution) public constant returns(uint256) {
if (getState() == State.PreSale) {
return getTokensForPreSale(exchangeRate, _totalETHContribution * 1 ether).div(10 ** 18);
}
return getNoOfTokens(exchangeRate, _totalETHContribution);
}
// provides the bonus %
function currentBonus(uint256 _ethContribution) public constant returns (uint8) {
if (getState() == State.PreSale) {
return getPreSaleBonusRate(_ethContribution * 1 ether);
}
return getCurrentBonusRate();
}
///////////////////////////////////// Presale Functions /////////////////////////////////////
// function to buy the tokens at presale with minimum investment = 10k USD
function buyPreSaleTokens(address beneficiary) internal returns(bool) {
// check the minimum investment should be 10k USD
if (msg.value < minAmount) {
revert();
} else {
fundTransfer(msg.value);
uint256 amount = getTokensForPreSale(exchangeRate, msg.value);
if (token.transfer(beneficiary, amount)) {
token.changeTotalSupply(amount);
totalWeiRaised = totalWeiRaised.add(msg.value);
TokenPurchase(beneficiary, msg.value, amount);
return true;
}
return false;
}
}
// function calculate the total no of tokens with bonus multiplication in the duration of presale
function getTokensForPreSale(uint256 _exchangeRate, uint256 _amount) internal returns (uint256) {
uint256 noOfToken = _amount.mul(_exchangeRate);
uint256 preSaleTokenQuantity = ((100 + getPreSaleBonusRate(_amount)) * noOfToken ).div(100);
return preSaleTokenQuantity;
}
function getPreSaleBonusRate(uint256 _ethAmount) internal returns (uint8) {
if ( _ethAmount >= minAmount.mul(5) && _ethAmount < minAmount.mul(10)) {
return 30;
}
if (_ethAmount >= minAmount.mul(10)) {
return 35;
}
if (_ethAmount >= minAmount) {
return 25;
}
}
///////////////////////////////////// Crowdfund Functions /////////////////////////////////////
// Starts the crowdfund, can only be called once
function startCrowdfund(uint256 _exchangeRate) onlyFounders tokenIsDeployed inState(State.PreSale) {
if (_exchangeRate > 0 && !hasCrowdFundStarted) {
exchangeRate = _exchangeRate;
crowdfundStartTime = now;
crowdfundEndTime = crowdfundStartTime + 5 * 1 weeks; // end date is 5 weeks after the starting date
isCrowdFundActive = !isCrowdFundActive;
hasCrowdFundStarted = !hasCrowdFundStarted;
} else {
revert();
}
}
// function call after crowdFundEndTime.
// It transfers the remaining tokens to remainingTokenHolder address
function endCrowdfund() onlyFounders returns (bool) {
require(now > crowdfundEndTime);
uint256 remainingToken = token.balanceOf(this); // remaining tokens
if (remainingToken != 0 && token.transfer(remainingTokenHolder, remainingToken)) {
return true;
} else {
return false;
}
CrowdFundClosed(now);
}
// function to calculate the total no of tokens with bonus multiplication
function getNoOfTokens(uint256 _exchangeRate, uint256 _amount) internal returns (uint256) {
uint256 noOfToken = _amount.mul(_exchangeRate);
uint256 noOfTokenWithBonus = ((100 + getCurrentBonusRate()) * noOfToken).div(100);
return noOfTokenWithBonus;
}
// function provide the current bonus rate
function getCurrentBonusRate() internal returns (uint8) {
if (now > crowdfundStartTime + 4 weeks) {
return 0;
}
if (now > crowdfundStartTime + 3 weeks) {
return 5;
}
if (now > crowdfundStartTime + 2 weeks) {
return 10;
}
if (now > crowdfundStartTime + 1 weeks) {
return 15;
}
if (now > crowdfundStartTime) {
return 20;
}
}
// Crowdfund entry
// send ether to the contract address
// With at least 200 000 gas
function() public payable {
buyTokens(msg.sender);
}
} | function to calculate the total no of tokens with bonus multiplication | function getNoOfTokens(uint256 _exchangeRate, uint256 _amount) internal returns (uint256) {
uint256 noOfToken = _amount.mul(_exchangeRate);
uint256 noOfTokenWithBonus = ((100 + getCurrentBonusRate()) * noOfToken).div(100);
return noOfTokenWithBonus;
}
| 931,230 | [
1,
915,
358,
4604,
326,
2078,
1158,
434,
2430,
598,
324,
22889,
23066,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
2279,
951,
5157,
12,
11890,
5034,
389,
16641,
4727,
16,
2254,
5034,
389,
8949,
13,
2713,
1135,
261,
11890,
5034,
13,
288,
203,
540,
2254,
5034,
1158,
951,
1345,
273,
389,
8949,
18,
16411,
24899,
16641,
4727,
1769,
203,
540,
2254,
5034,
1158,
951,
1345,
1190,
38,
22889,
273,
14015,
6625,
397,
5175,
38,
22889,
4727,
10756,
380,
1158,
951,
1345,
2934,
2892,
12,
6625,
1769,
203,
540,
327,
1158,
951,
1345,
1190,
38,
22889,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.5;
import "../interface/IERC20.sol";
import "../library/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interface/IGegoToken.sol";
import "../interface/IGegoFactory.sol";
import "../library/Governance.sol";
import "../library/DegoUtil.sol";
contract GegoFactory is Governance, IGegoFactory{
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
struct Gego {
uint256 id;
uint256 grade;
uint256 quality;
uint256 degoAmount;
uint256 createdTime;
uint256 blockNum;
uint256 resId;
address author;
}
event GegoAdded(
uint256 indexed id,
uint256 grade,
uint256 quality,
uint256 degoAmount,
uint256 createdTime,
uint256 blockNum,
uint256 resId,
address author
);
event GegoBurn(
uint256 indexed id,
uint256 degoAmount
);
event NFTReceived(address operator, address from, uint256 tokenId, bytes data);
// for minters
mapping(address => bool) public _minters;
mapping(uint256 => Gego) public _gegoes;
mapping(address => bool ) public _whitelist;
uint32 public _gegoId = 0;
uint256 public _minBurnTime = 1000*365 days;
uint256 public _qualityBase = 10000;
IERC20 public _dego = IERC20(0x0);
IERC20 public _airdropToken = IERC20(0x0);
IGegoToken public _gego = IGegoToken(0x0);
uint256 public _maxClaimCount = 40000;
uint256 public _currentClaimCount = 0;
bool public _isClaimStart = false;
mapping(address => bool) public _claimMembers;
uint256 public _maxClaimKryptonite = 20;
uint256 public _stakeDegoForKryptonite = 100 * (10**18);
uint256 public _currentClaimKryptonite = 0;
uint256 public _maxGrade = 6;
uint256 public _maxGradeLong = 20;
bool public _canMintToken = true;
uint256 public _mintDegoRate = 100;
constructor(address dego, address gego) public {
_dego = IERC20(dego);
_gego = IGegoToken(gego);
_airdropToken = IERC20(dego);
}
function setMaxClaimKryptonite(uint256 value) public onlyGovernance{
_maxClaimKryptonite = value;
}
function setClaimStart(bool start) public onlyGovernance {
_isClaimStart = start;
}
/**
* @dev for set min burn time
*/
function setMinBurnTime(uint256 minBurnTime) public onlyGovernance {
_minBurnTime = minBurnTime;
}
function addMinter(address minter) public onlyGovernance {
_minters[minter] = true;
}
function removeMinter(address minter) public onlyGovernance {
_minters[minter] = false;
}
function addWhitelist(address member) external onlyGovernance {
_whitelist[member] = true;
}
function removeWhitelist(address member) external onlyGovernance {
_whitelist[member] = false;
}
/// @dev batch set quota for user admin
/// if openTag <=0, removed
function setWhitelist(address[] calldata users, bool openTag)
external
onlyGovernance
{
for (uint256 i = 0; i < users.length; i++) {
_whitelist[users[i]] = openTag;
}
}
/**
* @dev set dego contract address
*/
function setDegoContract(address dego) public
onlyGovernance{
_dego = IERC20(dego);
}
/**
* @dev set gego contract address
*/
function setGegoContract(address gego) public
onlyGovernance{
_gego = IGegoToken(gego);
}
/**
* @dev set dandy contract address
*/
function setAirdropToken(address airdropToken) public
onlyGovernance{
_airdropToken = IERC20(airdropToken);
}
/**
* @dev set isCanMintToken
*/
function setCanMintToken(bool b) public
onlyGovernance{
_canMintToken = b;
}
/**
* @dev set maxClaimCount
*/
function setMaxClaimCount(uint256 maxClaimCount) public
onlyGovernance{
_maxClaimCount = maxClaimCount;
}
function setMintDegoRate(uint256 mintDegoRate) public onlyGovernance {
_mintDegoRate = mintDegoRate;
}
function getGego(uint256 tokenId)
external view
returns (
uint256 grade,
uint256 quality,
uint256 degoAmount,
uint256 createdTime,
uint256 blockNum,
uint256 resId,
address author
)
{
Gego storage gego = _gegoes[tokenId];
require(gego.id > 0, "not exist");
grade = gego.grade;
quality = gego.quality;
degoAmount = gego.degoAmount;
createdTime = gego.createdTime;
blockNum = gego.blockNum;
resId = gego.resId;
author = gego.author;
}
function getQualityBase() external view
returns (uint256 ){
return _qualityBase;
}
function computerSeed() private view returns (uint256) {
// from fomo3D
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)
)));
return seed;
}
function setResId(uint256 tokenId, uint256 resId) external onlyGovernance {
require( _gegoes[tokenId].id > 0, "not exist");
_gegoes[tokenId].resId = resId;
}
function getGrade(uint256 quality) public view returns (uint256){
if( quality < _qualityBase.mul(500).div(1000)){
return 1;
}else if( _qualityBase.mul(500).div(1000) <= quality && quality < _qualityBase.mul(800).div(1000)){
return 2;
}else if( _qualityBase.mul(800).div(1000) <= quality && quality < _qualityBase.mul(900).div(1000)){
return 3;
}else if( _qualityBase.mul(900).div(1000) <= quality && quality < _qualityBase.mul(980).div(1000)){
return 4;
}else if( _qualityBase.mul(980).div(1000) <= quality && quality < _qualityBase.mul(998).div(1000)){
return 5;
}else{
return 6;
}
}
function airdrop(uint32 gego_id, uint256 degoAmount, uint256 grade, uint256 quality, address author) public returns( uint256){
require(_minters[msg.sender] , "can't mint");
// change v6
if(grade == 6){
grade = grade.sub(1);
quality = quality.sub(_maxGradeLong);
degoAmount = 5 * (10**18);
}
uint256 gegoId = doMint(gego_id, degoAmount, grade, quality, grade, author);
return gegoId;
}
function claim() public returns( uint256){
require(_isClaimStart == true, "claim not start");
require(_claimMembers[msg.sender] == false, "has claim");
require(_whitelist[msg.sender] == true, "not in whitelist");
require(_currentClaimCount < _maxClaimCount, "claim enough");
uint256 quality = 0;
uint256 grade = 0;
uint256 degoAmount = 0;
uint256 seed = computerSeed();
quality = seed%_qualityBase;
grade = getGrade(quality);
if(grade == _maxGrade){
if( _currentClaimKryptonite >= _maxClaimKryptonite ){
grade = grade.sub(1);
quality = quality.sub(_maxGradeLong);
}else{
_currentClaimKryptonite = _currentClaimKryptonite.add(1);
}
}
degoAmount = grade * (10**18);
if(grade == _maxGrade ){
degoAmount = _stakeDegoForKryptonite;
}
uint256 gegoId = doMint(0, degoAmount, grade, quality, grade, msg.sender);
_claimMembers[msg.sender] = true;
if(_canMintToken){
_airdropToken.mint(msg.sender, degoAmount.div(_mintDegoRate));
}
_currentClaimCount = _currentClaimCount.add(1);
return gegoId;
}
/// @dev Creates a new card in the Cards contract and mints the token
// prettier-ignore
function doMint(uint32 gego_id, uint256 degoAmount, uint256 grade, uint256 quality, uint256 resId, address author) internal returns (uint256) {
require(degoAmount > 0, "must stake dego in nft");
if(gego_id == 0){
_gegoId++ ;
gego_id = _gegoId;
}else{
if(gego_id > _gegoId){
_gegoId = gego_id;
}
}
Gego memory gego;
gego.id = gego_id;
gego.blockNum = block.number;
gego.createdTime = block.timestamp ;
gego.grade = grade;
gego.quality = quality;
gego.degoAmount = degoAmount;
gego.author = author;
gego.resId = resId;
_gegoes[gego_id] = gego;
_gego.mint(author, gego_id);
emit GegoAdded(
gego.id,
gego.grade,
gego.quality,
gego.degoAmount,
gego.createdTime,
gego.blockNum,
gego.resId,
gego.author
);
return gego_id;
}
function burn(uint256 tokenId) external returns ( bool ) {
Gego memory gego = _gegoes[tokenId];
require(gego.id > 0, "not exist");
require( (block.timestamp - gego.createdTime) >= _minBurnTime, "< minBurnTime" );
// transfer nft to contract
_gego.safeTransferFrom(msg.sender, address(this), tokenId);
_gego.burn(tokenId);
_dego.safeTransfer(msg.sender, gego.degoAmount);
// set burn flag
emit GegoBurn(gego.id, gego.degoAmount);
gego.id = 0;
return true;
}
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4) {
//only receive the _nft staff
if(address(this) != operator) {
//invalid from nft
return 0;
}
//success
emit NFTReceived(operator, from, tokenId, data);
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
}
| * @dev set isCanMintToken/ | function setCanMintToken(bool b) public
onlyGovernance{
_canMintToken = b;
}
| 1,762,075 | [
1,
542,
353,
2568,
49,
474,
1345,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
2568,
49,
474,
1345,
12,
6430,
324,
13,
225,
1071,
21281,
3639,
1338,
43,
1643,
82,
1359,
95,
203,
3639,
389,
4169,
49,
474,
1345,
273,
225,
324,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xa9ff936f2631f4ed1D2503b1bF1f92bC7EA7434B/sources/contracts/ElixirMaster.sol | * @notice Return reward multiplier over the given _from to _to block./ | function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (IERC20(ELIXIR).totalSupply() >= maxSupply) {
return 0;
}
return _to.sub(_from);
}
| 14,253,362 | [
1,
990,
19890,
15027,
1879,
326,
864,
389,
2080,
358,
389,
869,
1203,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
31863,
5742,
12,
11890,
5034,
389,
2080,
16,
2254,
5034,
389,
869,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
309,
261,
45,
654,
39,
3462,
12,
41,
2053,
60,
7937,
2934,
4963,
3088,
1283,
1435,
1545,
943,
3088,
1283,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
327,
389,
869,
18,
1717,
24899,
2080,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
// File: contracts/InkMediator.sol
interface InkMediator {
function mediationExpiry() external returns (uint32);
function requestMediator(uint256 _transactionId, uint256 _transactionAmount, address _transactionOwner) external returns (bool);
function confirmTransactionFee(uint256 _transactionAmount) external returns (uint256);
function confirmTransactionAfterExpiryFee(uint256 _transactionAmount) external returns (uint256);
function confirmTransactionAfterDisputeFee(uint256 _transactionAmount) external returns (uint256);
function confirmTransactionByMediatorFee(uint256 _transactionAmount) external returns (uint256);
function refundTransactionFee(uint256 _transactionAmount) external returns (uint256);
function refundTransactionAfterExpiryFee(uint256 _transactionAmount) external returns (uint256);
function refundTransactionAfterDisputeFee(uint256 _transactionAmount) external returns (uint256);
function refundTransactionByMediatorFee(uint256 _transactionAmount) external returns (uint256);
function settleTransactionByMediatorFee(uint256 _buyerAmount, uint256 _sellerAmount) external returns (uint256, uint256);
}
// File: contracts/InkOwner.sol
interface InkOwner {
function authorizeTransaction(uint256 _id, address _buyer) external returns (bool);
}
// File: contracts/InkProtocolInterface.sol
interface InkProtocolInterface {
// Event emitted when a transaction is initiated.
event TransactionInitiated(
uint256 indexed id,
address owner,
address indexed buyer,
address indexed seller,
address policy,
address mediator,
uint256 amount,
// A hash string representing the metadata for the transaction. This is
// somewhat arbitrary for the transaction. Only the transaction owner
// will really know the original contents of the metadata and may choose
// to share it at their discretion.
bytes32 metadata
);
// Event emitted when a transaction has been accepted by the seller.
event TransactionAccepted(
uint256 indexed id
);
// Event emitted when a transaction has been disputed by the buyer.
event TransactionDisputed(
uint256 indexed id
);
// Event emitted when a transaction is escalated to the mediator by the
// seller.
event TransactionEscalated(
uint256 indexed id
);
// Event emitted when a transaction is revoked by the seller.
event TransactionRevoked(
uint256 indexed id
);
// Event emitted when a transaction is revoked by the seller.
event TransactionRefundedByMediator(
uint256 indexed id,
uint256 mediatorFee
);
// Event emitted when a transaction is settled by the mediator.
event TransactionSettledByMediator(
uint256 indexed id,
uint256 buyerAmount,
uint256 sellerAmount,
uint256 buyerMediatorFee,
uint256 sellerMediatorFee
);
// Event emitted when a transaction is confirmed by the mediator.
event TransactionConfirmedByMediator(
uint256 indexed id,
uint256 mediatorFee
);
// Event emitted when a transaction is confirmed by the buyer.
event TransactionConfirmed(
uint256 indexed id,
uint256 mediatorFee
);
// Event emitted when a transaction is refunded by the seller.
event TransactionRefunded(
uint256 indexed id,
uint256 mediatorFee
);
// Event emitted when a transaction is confirmed by the seller after the
// transaction expiry.
event TransactionConfirmedAfterExpiry(
uint256 indexed id,
uint256 mediatorFee
);
// Event emitted when a transaction is confirmed by the buyer after it was
// disputed.
event TransactionConfirmedAfterDispute(
uint256 indexed id,
uint256 mediatorFee
);
// Event emitted when a transaction is refunded by the seller after it was
// disputed.
event TransactionRefundedAfterDispute(
uint256 indexed id,
uint256 mediatorFee
);
// Event emitted when a transaction is refunded by the buyer after the
// escalation expiry.
event TransactionRefundedAfterExpiry(
uint256 indexed id,
uint256 mediatorFee
);
// Event emitted when a transaction is confirmed by the buyer after the
// mediation expiry.
event TransactionConfirmedAfterEscalation(
uint256 indexed id
);
// Event emitted when a transaction is refunded by the seller after the
// mediation expiry.
event TransactionRefundedAfterEscalation(
uint256 indexed id
);
// Event emitted when a transaction is settled by either the buyer or the
// seller after the mediation expiry.
event TransactionSettled(
uint256 indexed id,
uint256 buyerAmount,
uint256 sellerAmount
);
// Event emitted when a transaction's feedback is updated by the buyer.
event FeedbackUpdated(
uint256 indexed transactionId,
uint8 rating,
bytes32 comment
);
// Event emitted an account is (unidirectionally) linked to another account.
// For two accounts to be acknowledged as linked, the linkage must be
// bidirectional.
event AccountLinked(
address indexed from,
address indexed to
);
/* Protocol */
function link(address _to) external;
function createTransaction(address _seller, uint256 _amount, bytes32 _metadata, address _policy, address _mediator) external returns (uint256);
function createTransaction(address _seller, uint256 _amount, bytes32 _metadata, address _policy, address _mediator, address _owner) external returns (uint256);
function revokeTransaction(uint256 _id) external;
function acceptTransaction(uint256 _id) external;
function confirmTransaction(uint256 _id) external;
function confirmTransactionAfterExpiry(uint256 _id) external;
function refundTransaction(uint256 _id) external;
function refundTransactionAfterExpiry(uint256 _id) external;
function disputeTransaction(uint256 _id) external;
function escalateDisputeToMediator(uint256 _id) external;
function settleTransaction(uint256 _id) external;
function refundTransactionByMediator(uint256 _id) external;
function confirmTransactionByMediator(uint256 _id) external;
function settleTransactionByMediator(uint256 _id, uint256 _buyerAmount, uint256 _sellerAmount) external;
function provideTransactionFeedback(uint256 _id, uint8 _rating, bytes32 _comment) external;
/* ERC20 */
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function increaseApproval(address spender, uint addedValue) public returns (bool);
function decreaseApproval(address spender, uint subtractedValue) public returns (bool);
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/InkProtocolCore.sol
/// @title Ink Protocol: Decentralized reputation and payments for peer-to-peer marketplaces.
contract InkProtocolCore is InkProtocolInterface, StandardToken {
string public constant name = "Ink Protocol";
string public constant symbol = "XNK";
uint8 public constant decimals = 18;
uint256 private constant gasLimitForExpiryCall = 1000000;
uint256 private constant gasLimitForMediatorCall = 4000000;
enum Expiry {
Transaction, // 0
Fulfillment, // 1
Escalation, // 2
Mediation // 3
}
enum TransactionState {
// This is an internal state to represent an uninitialized transaction.
Null, // 0
Initiated, // 1
Accepted, // 2
Disputed, // 3
Escalated, // 4
Revoked, // 5
RefundedByMediator, // 6
SettledByMediator, // 7
ConfirmedByMediator, // 8
Confirmed, // 9
Refunded, // 10
ConfirmedAfterExpiry, // 11
ConfirmedAfterDispute, // 12
RefundedAfterDispute, // 13
RefundedAfterExpiry, // 14
ConfirmedAfterEscalation, // 15
RefundedAfterEscalation, // 16
Settled // 17
}
// The running ID counter for all Ink Transactions.
uint256 private globalTransactionId = 0;
// Mapping of all transactions by ID (globalTransactionId).
mapping(uint256 => Transaction) internal transactions;
// The struct definition for an Ink Transaction.
struct Transaction {
// The address of the buyer on the transaction.
address buyer;
// The address of the seller on the transaction.
address seller;
// The address of the policy contract for the transaction.
address policy;
// The address of the mediator contract for the transaction.
address mediator;
// The state of the transaction.
TransactionState state;
// The (block) time that the transaction transitioned to its current state.
// This value is only set for the states that need it to be set (states
// with an expiry involved).
uint256 stateTime;
// The XNK amount of the transaction.
uint256 amount;
}
/*
Constructor
*/
function InkProtocolCore() internal {
// Start with a total supply of 500,000,000 Ink Tokens (XNK).
totalSupply_ = 500000000000000000000000000;
}
/*
ERC20 override functions
*/
function transfer(address _to, uint256 _value) public returns (bool) {
// Don't allow token transfers to the Ink contract.
require(_to != address(this));
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// Don't allow token transfers to the Ink contract.
require(_to != address(this));
return super.transferFrom(_from, _to, _value);
}
/*
Account linking functions
Functions used by users and agents to declare a unidirectionally account
linking.
*/
// Called by a user who wishes to link with another _account.
function link(address _to) external {
require(_to != address(0));
require(_to != msg.sender);
AccountLinked({
from: msg.sender,
to: _to
});
}
/*
Transaction functions
*/
function createTransaction(address _seller, uint256 _amount, bytes32 _metadata, address _policy, address _mediator) external returns (uint256) {
return _createTransaction(_seller, _amount, _metadata, _policy, _mediator, address(0));
}
function createTransaction(address _seller, uint256 _amount, bytes32 _metadata, address _policy, address _mediator, address _owner) external returns (uint256) {
return _createTransaction(_seller, _amount, _metadata, _policy, _mediator, _owner);
}
function revokeTransaction(uint256 _id) external {
_revokeTransaction(_id, _findTransactionForBuyer(_id));
}
function acceptTransaction(uint256 _id) external {
_acceptTransaction(_id, _findTransactionForSeller(_id));
}
function confirmTransaction(uint256 _id) external {
_confirmTransaction(_id, _findTransactionForBuyer(_id));
}
function confirmTransactionAfterExpiry(uint256 _id) external {
_confirmTransactionAfterExpiry(_id, _findTransactionForSeller(_id));
}
function refundTransaction(uint256 _id) external {
_refundTransaction(_id, _findTransactionForSeller(_id));
}
function refundTransactionAfterExpiry(uint256 _id) external {
_refundTransactionAfterExpiry(_id, _findTransactionForBuyer(_id));
}
function disputeTransaction(uint256 _id) external {
_disputeTransaction(_id, _findTransactionForBuyer(_id));
}
function escalateDisputeToMediator(uint256 _id) external {
_escalateDisputeToMediator(_id, _findTransactionForSeller(_id));
}
function settleTransaction(uint256 _id) external {
_settleTransaction(_id, _findTransactionForParty(_id));
}
function refundTransactionByMediator(uint256 _id) external {
_refundTransactionByMediator(_id, _findTransactionForMediator(_id));
}
function confirmTransactionByMediator(uint256 _id) external {
_confirmTransactionByMediator(_id, _findTransactionForMediator(_id));
}
function settleTransactionByMediator(uint256 _id, uint256 _buyerAmount, uint256 _sellerAmount) external {
_settleTransactionByMediator(_id, _findTransactionForMediator(_id), _buyerAmount, _sellerAmount);
}
function provideTransactionFeedback(uint256 _id, uint8 _rating, bytes32 _comment) external {
_provideTransactionFeedback(_id, _findTransactionForBuyer(_id), _rating, _comment);
}
/*
Private functions
*/
function _createTransaction(address _seller, uint256 _amount, bytes32 _metadata, address _policy, address _mediator, address _owner) private returns (uint256) {
require(_seller != address(0) && _seller != msg.sender);
require(_owner != msg.sender && _owner != _seller);
require(_amount > 0);
// Per specifications, if a mediator is involved then a policy is required.
// Otherwise, policy must be a zero address.
if (_mediator == address(0)) {
require(_policy == address(0));
} else {
require(_policy != address(0));
}
// Increment the transaction.
uint256 id = globalTransactionId++;
// Create the transaction.
Transaction storage transaction = transactions[id];
transaction.buyer = msg.sender;
transaction.seller = _seller;
transaction.state = TransactionState.Initiated;
transaction.amount = _amount;
transaction.policy = _policy;
_resolveMediator(id, transaction, _mediator, _owner);
_resolveOwner(id, _owner);
// Emit the event.
TransactionInitiated({
id: id,
owner: _owner,
buyer: msg.sender,
seller: _seller,
policy: _policy,
mediator: _mediator,
amount: _amount,
metadata: _metadata
});
// Place the buyer's tokens in escrow (ie. this contract).
_transferFrom(msg.sender, this, _amount);
// Return the newly created transaction's id.
return id;
}
function _revokeTransaction(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Initiated);
TransactionRevoked({ id: _id });
_transferFromEscrow(_transaction.buyer, _transaction.amount);
_cleanupTransaction(_id, _transaction, false);
}
function _acceptTransaction(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Initiated);
if (_transaction.mediator != address(0)) {
_updateTransactionState(_transaction, TransactionState.Accepted);
}
TransactionAccepted({ id: _id });
if (_transaction.mediator == address(0)) {
// If there is no mediator involved, the transaction is immediately confirmed.
_completeTransaction(_id, _transaction, TransactionState.Confirmed, _transaction.seller);
}
}
function _confirmTransaction(uint256 _id, Transaction storage _transaction) private {
TransactionState finalState;
if (_transaction.state == TransactionState.Accepted) {
finalState = TransactionState.Confirmed;
} else if (_transaction.state == TransactionState.Disputed) {
finalState = TransactionState.ConfirmedAfterDispute;
} else if (_transaction.state == TransactionState.Escalated) {
require(_afterExpiry(_transaction, _fetchExpiry(_transaction, Expiry.Mediation)));
finalState = TransactionState.ConfirmedAfterEscalation;
} else {
revert();
}
_completeTransaction(_id, _transaction, finalState, _transaction.seller);
}
function _confirmTransactionAfterExpiry(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Accepted);
require(_afterExpiry(_transaction, _fetchExpiry(_transaction, Expiry.Transaction)));
_completeTransaction(_id, _transaction, TransactionState.ConfirmedAfterExpiry, _transaction.seller);
}
function _refundTransaction(uint256 _id, Transaction storage _transaction) private {
TransactionState finalState;
if (_transaction.state == TransactionState.Accepted) {
finalState = TransactionState.Refunded;
} else if (_transaction.state == TransactionState.Disputed) {
finalState = TransactionState.RefundedAfterDispute;
} else if (_transaction.state == TransactionState.Escalated) {
require(_afterExpiry(_transaction, _fetchExpiry(_transaction, Expiry.Mediation)));
finalState = TransactionState.RefundedAfterEscalation;
} else {
revert();
}
_completeTransaction(_id, _transaction, finalState, _transaction.buyer);
}
function _refundTransactionAfterExpiry(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Disputed);
require(_afterExpiry(_transaction, _fetchExpiry(_transaction, Expiry.Escalation)));
_completeTransaction(_id, _transaction, TransactionState.RefundedAfterExpiry, _transaction.buyer);
}
function _disputeTransaction(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Accepted);
require(_afterExpiry(_transaction, _fetchExpiry(_transaction, Expiry.Fulfillment)));
_updateTransactionState(_transaction, TransactionState.Disputed);
TransactionDisputed({ id: _id });
}
function _escalateDisputeToMediator(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Disputed);
_updateTransactionState(_transaction, TransactionState.Escalated);
TransactionEscalated({ id: _id });
}
function _settleTransaction(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Escalated);
require(_afterExpiry(_transaction, _fetchExpiry(_transaction, Expiry.Mediation)));
// Divide the escrow amount in half and give it to the buyer. There's
// a possibility that one account will get slightly more than the other.
// We have decided to give the lesser amount to the buyer (arbitrarily).
uint256 buyerAmount = _transaction.amount.div(2);
// The remaining amount is given to the seller.
uint256 sellerAmount = _transaction.amount.sub(buyerAmount);
TransactionSettled({
id: _id,
buyerAmount: buyerAmount,
sellerAmount: sellerAmount
});
_transferFromEscrow(_transaction.buyer, buyerAmount);
_transferFromEscrow(_transaction.seller, sellerAmount);
_cleanupTransaction(_id, _transaction, true);
}
function _refundTransactionByMediator(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Escalated);
_completeTransaction(_id, _transaction, TransactionState.RefundedByMediator, _transaction.buyer);
}
function _confirmTransactionByMediator(uint256 _id, Transaction storage _transaction) private {
require(_transaction.state == TransactionState.Escalated);
_completeTransaction(_id, _transaction, TransactionState.ConfirmedByMediator, _transaction.seller);
}
function _settleTransactionByMediator(uint256 _id, Transaction storage _transaction, uint256 _buyerAmount, uint256 _sellerAmount) private {
require(_transaction.state == TransactionState.Escalated);
require(_buyerAmount.add(_sellerAmount) == _transaction.amount);
uint256 buyerMediatorFee;
uint256 sellerMediatorFee;
(buyerMediatorFee, sellerMediatorFee) = InkMediator(_transaction.mediator).settleTransactionByMediatorFee(_buyerAmount, _sellerAmount);
// Require that the sum of the fees be no more than the transaction's amount.
require(buyerMediatorFee <= _buyerAmount && sellerMediatorFee <= _sellerAmount);
TransactionSettledByMediator({
id: _id,
buyerAmount: _buyerAmount,
sellerAmount: _sellerAmount,
buyerMediatorFee: buyerMediatorFee,
sellerMediatorFee: sellerMediatorFee
});
_transferFromEscrow(_transaction.buyer, _buyerAmount.sub(buyerMediatorFee));
_transferFromEscrow(_transaction.seller, _sellerAmount.sub(sellerMediatorFee));
_transferFromEscrow(_transaction.mediator, buyerMediatorFee.add(sellerMediatorFee));
_cleanupTransaction(_id, _transaction, true);
}
function _provideTransactionFeedback(uint256 _id, Transaction storage _transaction, uint8 _rating, bytes32 _comment) private {
// The transaction must be completed (Null state with a buyer) to allow
// feedback.
require(_transaction.state == TransactionState.Null);
// As per functional specifications, ratings must be an integer between
// 1 and 5, inclusive.
require(_rating >= 1 && _rating <= 5);
FeedbackUpdated({
transactionId: _id,
rating: _rating,
comment: _comment
});
}
function _completeTransaction(uint256 _id, Transaction storage _transaction, TransactionState _finalState, address _transferTo) private {
uint256 mediatorFee = _fetchMediatorFee(_transaction, _finalState);
if (_finalState == TransactionState.Confirmed) {
TransactionConfirmed({ id: _id, mediatorFee: mediatorFee });
} else if (_finalState == TransactionState.ConfirmedAfterDispute) {
TransactionConfirmedAfterDispute({ id: _id, mediatorFee: mediatorFee });
} else if (_finalState == TransactionState.ConfirmedAfterEscalation) {
TransactionConfirmedAfterEscalation({ id: _id });
} else if (_finalState == TransactionState.ConfirmedAfterExpiry) {
TransactionConfirmedAfterExpiry({ id: _id, mediatorFee: mediatorFee });
} else if (_finalState == TransactionState.Refunded) {
TransactionRefunded({ id: _id, mediatorFee: mediatorFee });
} else if (_finalState == TransactionState.RefundedAfterDispute) {
TransactionRefundedAfterDispute({ id: _id, mediatorFee: mediatorFee });
} else if (_finalState == TransactionState.RefundedAfterEscalation) {
TransactionRefundedAfterEscalation({ id: _id });
} else if (_finalState == TransactionState.RefundedAfterExpiry) {
TransactionRefundedAfterExpiry({ id: _id, mediatorFee: mediatorFee });
} else if (_finalState == TransactionState.RefundedByMediator) {
TransactionRefundedByMediator({ id: _id, mediatorFee: mediatorFee });
} else if (_finalState == TransactionState.ConfirmedByMediator) {
TransactionConfirmedByMediator({ id: _id, mediatorFee: mediatorFee });
}
_transferFromEscrow(_transferTo, _transaction.amount.sub(mediatorFee));
_transferFromEscrow(_transaction.mediator, mediatorFee);
_cleanupTransaction(_id, _transaction, true);
}
function _fetchExpiry(Transaction storage _transaction, Expiry _expiryType) private returns (uint32) {
uint32 expiry;
bool success;
if (_expiryType == Expiry.Transaction) {
success = _transaction.policy.call.gas(gasLimitForExpiryCall)(bytes4(keccak256("transactionExpiry()")));
} else if (_expiryType == Expiry.Fulfillment) {
success = _transaction.policy.call.gas(gasLimitForExpiryCall)(bytes4(keccak256("fulfillmentExpiry()")));
} else if (_expiryType == Expiry.Escalation) {
success = _transaction.policy.call.gas(gasLimitForExpiryCall)(bytes4(keccak256("escalationExpiry()")));
} else if (_expiryType == Expiry.Mediation) {
success = _transaction.mediator.call.gas(gasLimitForExpiryCall)(bytes4(keccak256("mediationExpiry()")));
}
if (success) {
assembly {
if eq(returndatasize(), 0x20) {
let _freeMemPointer := mload(0x40)
returndatacopy(_freeMemPointer, 0, 0x20)
expiry := mload(_freeMemPointer)
}
}
}
return expiry;
}
function _fetchMediatorFee(Transaction storage _transaction, TransactionState _finalState) private returns (uint256) {
if (_transaction.mediator == address(0)) {
return 0;
}
uint256 mediatorFee;
bool success;
if (_finalState == TransactionState.Confirmed) {
success = _transaction.mediator.call.gas(gasLimitForMediatorCall)(bytes4(keccak256("confirmTransactionFee(uint256)")), _transaction.amount);
} else if (_finalState == TransactionState.ConfirmedAfterExpiry) {
success = _transaction.mediator.call.gas(gasLimitForMediatorCall)(bytes4(keccak256("confirmTransactionAfterExpiryFee(uint256)")), _transaction.amount);
} else if (_finalState == TransactionState.ConfirmedAfterDispute) {
success = _transaction.mediator.call.gas(gasLimitForMediatorCall)(bytes4(keccak256("confirmTransactionAfterDisputeFee(uint256)")), _transaction.amount);
} else if (_finalState == TransactionState.ConfirmedByMediator) {
mediatorFee = InkMediator(_transaction.mediator).confirmTransactionByMediatorFee(_transaction.amount);
} else if (_finalState == TransactionState.Refunded) {
success = _transaction.mediator.call.gas(gasLimitForMediatorCall)(bytes4(keccak256("refundTransactionFee(uint256)")), _transaction.amount);
} else if (_finalState == TransactionState.RefundedAfterExpiry) {
success = _transaction.mediator.call.gas(gasLimitForMediatorCall)(bytes4(keccak256("refundTransactionAfterExpiryFee(uint256)")), _transaction.amount);
} else if (_finalState == TransactionState.RefundedAfterDispute) {
success = _transaction.mediator.call.gas(gasLimitForMediatorCall)(bytes4(keccak256("refundTransactionAfterDisputeFee(uint256)")), _transaction.amount);
} else if (_finalState == TransactionState.RefundedByMediator) {
mediatorFee = InkMediator(_transaction.mediator).refundTransactionByMediatorFee(_transaction.amount);
}
if (success) {
assembly {
if eq(returndatasize(), 0x20) {
let _freeMemPointer := mload(0x40)
returndatacopy(_freeMemPointer, 0, 0x20)
mediatorFee := mload(_freeMemPointer)
}
}
// The mediator's fee cannot be more than transaction's amount.
if (mediatorFee > _transaction.amount) {
mediatorFee = 0;
}
} else {
require(mediatorFee <= _transaction.amount);
}
return mediatorFee;
}
function _resolveOwner(uint256 _transactionId, address _owner) private {
if (_owner != address(0)) {
// If an owner is specified, it must authorize the transaction.
require(InkOwner(_owner).authorizeTransaction(
_transactionId,
msg.sender
));
}
}
function _resolveMediator(uint256 _transactionId, Transaction storage _transaction, address _mediator, address _owner) private {
if (_mediator != address(0)) {
// The mediator must accept the transaction otherwise we abort.
require(InkMediator(_mediator).requestMediator(_transactionId, _transaction.amount, _owner));
// Assign the mediator to the transaction.
_transaction.mediator = _mediator;
}
}
function _afterExpiry(Transaction storage _transaction, uint32 _expiry) private view returns (bool) {
return now.sub(_transaction.stateTime) >= _expiry;
}
function _findTransactionForBuyer(uint256 _id) private view returns (Transaction storage transaction) {
transaction = _findTransaction(_id);
require(msg.sender == transaction.buyer);
}
function _findTransactionForSeller(uint256 _id) private view returns (Transaction storage transaction) {
transaction = _findTransaction(_id);
require(msg.sender == transaction.seller);
}
function _findTransactionForParty(uint256 _id) private view returns (Transaction storage transaction) {
transaction = _findTransaction(_id);
require(msg.sender == transaction.buyer || msg.sender == transaction.seller);
}
function _findTransactionForMediator(uint256 _id) private view returns (Transaction storage transaction) {
transaction = _findTransaction(_id);
require(msg.sender == transaction.mediator);
}
function _findTransaction(uint256 _id) private view returns (Transaction storage transaction) {
transaction = transactions[_id];
require(_id < globalTransactionId);
}
function _transferFrom(address _from, address _to, uint256 _value) private returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function _transferFromEscrow(address _to, uint256 _value) private returns (bool) {
if (_value > 0) {
return _transferFrom(this, _to, _value);
}
return true;
}
function _updateTransactionState(Transaction storage _transaction, TransactionState _state) private {
_transaction.state = _state;
_transaction.stateTime = now;
}
function _cleanupTransaction(uint256 _id, Transaction storage _transaction, bool _completed) private {
// Remove data that is no longer needed on the contract.
if (_completed) {
delete _transaction.state;
delete _transaction.seller;
delete _transaction.policy;
delete _transaction.mediator;
delete _transaction.stateTime;
delete _transaction.amount;
} else {
delete transactions[_id];
}
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
// File: zeppelin-solidity/contracts/token/ERC20/TokenVesting.sol
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
// File: contracts/InkProtocol.sol
/// @title Ink Protocol: Decentralized reputation and payments for peer-to-peer marketplaces.
contract InkProtocol is InkProtocolCore {
// Allocation addresses.
address public constant __address0__ = 0xA13febeEde2B2924Ce8b27c1512874D3576fEC16;
address public constant __address1__ = 0xc5bA7157b5B69B0fAe9332F30719Eecd79649486;
address public constant __address2__ = 0x29a4b44364A8Bcb6e4d9dd60c222cCaca286ebf2;
address public constant __address3__ = 0xc1DC1e5C3970E22201C5DAB0841abB2DD6499D3F;
address public constant __address4__ = 0x0746d0b67BED258d94D06b15859df8dbd990eC3D;
/*
Constructor for Mainnet.
*/
function InkProtocol() public {
// Unsold tokens due to token sale hard cap.
balances[__address0__] = 19625973697895500000000000;
Transfer(address(0), __address0__, balanceOf(__address0__));
// Allocate 32% to contract for distribution.
// Vesting starts Feb 28, 2018 @ 00:00:00 GMT
TokenVesting vesting1 = new TokenVesting(__address1__, 1519776000, 0, 3 years, false);
balances[vesting1] = 160000000000000000000000000;
Transfer(address(0), vesting1, balanceOf(vesting1));
// Allocate 32% to contract for Listia Inc.
// Vesting starts Feb 28, 2018 @ 00:00:00 GMT
TokenVesting vesting2 = new TokenVesting(__address2__, 1519776000, 0, 3 years, false);
balances[vesting2] = 160000000000000000000000000;
Transfer(address(0), vesting2, balanceOf(vesting2));
// Allocate 6% to wallet for Listia Marketplace credit conversion.
balances[__address3__] = 30000000000000000000000000;
Transfer(address(0), __address3__, balanceOf(__address3__));
// Allocate to wallet for token sale distribution.
balances[__address4__] = 130374026302104500000000000;
Transfer(address(0), __address4__, balanceOf(__address4__));
}
} | The struct definition for an Ink Transaction. The address of the buyer on the transaction. The address of the seller on the transaction. The address of the policy contract for the transaction. The address of the mediator contract for the transaction. The state of the transaction. The (block) time that the transaction transitioned to its current state. This value is only set for the states that need it to be set (states with an expiry involved). The XNK amount of the transaction. | struct Transaction {
address buyer;
address seller;
address policy;
address mediator;
TransactionState state;
uint256 stateTime;
uint256 amount;
}
| 5,460,639 | [
1,
1986,
1958,
2379,
364,
392,
657,
79,
5947,
18,
1021,
1758,
434,
326,
27037,
603,
326,
2492,
18,
1021,
1758,
434,
326,
29804,
603,
326,
2492,
18,
1021,
1758,
434,
326,
3329,
6835,
364,
326,
2492,
18,
1021,
1758,
434,
326,
6735,
10620,
6835,
364,
326,
2492,
18,
1021,
919,
434,
326,
2492,
18,
1021,
261,
2629,
13,
813,
716,
326,
2492,
6007,
329,
358,
2097,
783,
919,
18,
1220,
460,
353,
1338,
444,
364,
326,
5493,
716,
1608,
518,
358,
506,
444,
261,
7992,
598,
392,
10839,
24589,
2934,
1021,
1139,
50,
47,
3844,
434,
326,
2492,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
1958,
5947,
288,
203,
565,
1758,
27037,
31,
203,
565,
1758,
29804,
31,
203,
565,
1758,
3329,
31,
203,
565,
1758,
6735,
10620,
31,
203,
565,
5947,
1119,
919,
31,
203,
565,
2254,
5034,
919,
950,
31,
203,
565,
2254,
5034,
3844,
31,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x883EfA22c4E1C156Db5f3aE6C3E77be23135f424/sources/helshiContract.sol | (_totalSupply * 10) / 1000 [this equals 1%]
| uint256 public _maxTxAmount = (_totalSupply * 1000) / 1000; | 2,676,399 | [
1,
24899,
4963,
3088,
1283,
225,
1728,
13,
342,
4336,
306,
2211,
1606,
404,
9,
65,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
389,
1896,
4188,
6275,
273,
261,
67,
4963,
3088,
1283,
380,
4336,
13,
342,
4336,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract LANCCrowdsale is Ownable {
using SafeMath for uint256;
address public fundDepositAddress = 0xE700569B98D4BF25E05c64C96560f77bCD44565E;
uint256 public currentPeriod = 0;
bool public isFinalized = false;
// 0 = Not Started
// 1 = PrePresale
// 2 = Presale
// 3 = Round 1
// 4 = Round 2
// 5 = Finished
mapping (uint256 => uint256) public rateMap;
mapping (address => uint256) powerDayAddressLimits;
uint256 public powerDayRate;
uint256 public powerDayEthPerPerson = 10;
uint256 public presaleStartTime;
uint256 public powerDayEndTime;
uint256 public constant capPresale = 57 * (10**5) * 10**18;
uint256 public constant capRound1 = (288 * (10**5) * 10**18);
uint256 public constant capRound2 = (484 * (10**5) * 10**18);
uint256 public rate = 0; // LANC per ETH
// The token being sold
LANCToken public token;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function LANCCrowdsale() public {
// Initilize with rates.
rateMap[1] = 2100; // PrePresale rate
powerDayRate = 2000; // Powerday rate in presale.
rateMap[2] = 1900; // Presale rate
rateMap[3] = 1650; // Round 1 rate
rateMap[4] = 1400; // Round 2 rate
rateMap[5] = 0;
}
function setTokenContract(address _token) public onlyOwner {
require(_token != address(0) && token == address(0));
require(LANCToken(_token).owner() == address(this));
require(LANCToken(_token).totalSupply() == 0);
require(!LANCToken(_token).mintingFinished());
token = LANCToken(_token);
}
function mint(address _to, uint256 _amount) public onlyOwner {
require(token != address(0));
require(!LANCToken(token).mintingFinished());
require(LANCToken(token).owner() == address(this));
token.mint(_to, _amount);
}
// Backup function in case of ETH price fluctuations
function updateRates(uint256 rateIdx, uint256 newRate) public onlyOwner {
require(rateIdx > 0 && rateIdx < 5);
require(newRate > 0);
rateMap[rateIdx] = newRate;
if (rateIdx == currentPeriod) {
rate = newRate;
}
}
function updatePowerDayRate(uint256 newRate) public onlyOwner {
powerDayRate = newRate;
}
function switchSaleState() public onlyOwner {
require(token != address(0));
if (currentPeriod > 4) {
revert(); // Finished, last state is 4
}
currentPeriod = currentPeriod + 1;
if (currentPeriod == 2) {
presaleStartTime = now;
powerDayEndTime = (presaleStartTime + 1 days);
}
rate = rateMap[currentPeriod];
}
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(token != address(0));
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 currentRate = rate;
uint256 tokens;
bool inPowerDay = saleInPowerDay();
// calculate token amount to be created
// Assign power day rate if in power day.
if (inPowerDay == true) {
tokens = weiAmount.mul(powerDayRate);
} else {
tokens = weiAmount.mul(currentRate);
}
// calculate supply after potential token mint
uint256 checkedSupply = token.totalSupply().add(tokens);
require(willFitInCap(checkedSupply));
// check if new supply fits within current cap.
if (inPowerDay == true) {
uint256 newWeiAmountPerSender = powerDayAddressLimits[msg.sender].add(weiAmount);
// Check if the person has reached their power day limit.
if (newWeiAmountPerSender > powerDayPerPersonCapInWei()) {
revert();
} else {
powerDayAddressLimits[msg.sender] = newWeiAmountPerSender;
}
}
// Generate the tokens by using MintableToken's mint method.
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function saleInPowerDay() internal view returns (bool) {
bool inPresale = (currentPeriod == 2);
bool inPowerDayPeriod = (now >= presaleStartTime && now <= powerDayEndTime);
return inPresale && inPowerDayPeriod;
}
function powerDayPerPersonCapInWei() public view returns (uint) {
require(token != address(0));
// Calculate per-person cap in wei during power day.
return powerDayEthPerPerson * (10**token.decimals());
}
function willFitInCap(uint256 checkedSupply) internal view returns (bool) {
if (currentPeriod == 1 || currentPeriod == 2) {
return (checkedSupply <= capPresale);
} else if (currentPeriod == 3) {
return (checkedSupply <= capRound1);
} else if (currentPeriod == 4) {
return (checkedSupply <= capRound2);
}
return false;
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool tokenAssigned = (token != address(0));
bool inStartedState = (currentPeriod > 0 && currentPeriod < 5);
bool nonZeroPurchase = msg.value != 0;
return tokenAssigned && inStartedState && nonZeroPurchase && !isFinalized;
}
// Finalize the sale and calculate final token supply and distribute amounts.
function finalizeSale() public onlyOwner {
if (isFinalized == true) {
revert();
}
uint newTokens = token.totalSupply();
// Raise the remaining amounts
token.mint(fundDepositAddress, newTokens);
token.finishMinting();
token.transferOwnership(owner);
isFinalized = true;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return currentPeriod > 4;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
fundDepositAddress.transfer(msg.value);
}
function powerDayRemainingLimitOf(address _owner) public view returns (uint256 balance) {
return powerDayAddressLimits[_owner];
}
}
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 StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract LANCToken is MintableToken {
string public name = "LanceChain Token";
string public symbol = "LANC";
uint public decimals = 18;
} | @return true if crowdsale event has ended | function hasEnded() public view returns (bool) {
return currentPeriod > 4;
}
| 2,494,988 | [
1,
2463,
638,
309,
276,
492,
2377,
5349,
871,
711,
16926,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
711,
28362,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
565,
327,
783,
5027,
405,
1059,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/math/SafeMath.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/token/ERC20/SafeERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/utils/ReentrancyGuard.sol";
import "./PawToken.sol";
import "./libs/IRewardLocker.sol";
// MasterChef is the master of PAW. He can make PAW and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once PAW is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
// For any questions contact @macatkevin on Telegram
contract MasterChefv2 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 lastPawPerShare; // Paw per share on last update
uint256 unclaimed; // Unclaimed reward in Paw.
// pending reward = user.unclaimed + (user.amount * (pool.accPawPerShare - user.lastPawPerShare)
//
// Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens:
// 1. The pool's `accPawPerShare` (and `lastPawBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `lastPawPerShare` gets updated.
// 4. User's `amount` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. PAW to distribute per block.
uint256 totalDeposited; // The total deposited by users
uint256 lastRewardBlock; // Last block number that PAW distribution occurs.
uint256 accPawPerShare; // Accumulated PAW per share, times 1e18. See below.
}
// The PAW TOKEN!
PawToken public immutable paw;
address public pawTransferOwner;
address public devAddress;
// Contract for locking reward
IRewardLocker public immutable rewardLocker;
// PAW tokens created per block.
uint256 public pawPerBlock = 8 ether;
uint256 public constant MAX_EMISSION_RATE = 1000 ether; // Safety check
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
uint256 public constant MAX_ALLOC_POINT = 100000; // Safety check
// The block number when PAW mining starts.
uint256 public immutable startBlock;
event Add(address indexed user, uint256 allocPoint, IERC20 indexed token, bool massUpdatePools);
event Set(address indexed user, uint256 pid, uint256 allocPoint);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, bool harvest);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, bool harvest);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event HarvestMultiple(address indexed user, uint256[] _pids, uint256 amount);
event HarvestAll(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SetDevAddress(address indexed user, address indexed newAddress);
event UpdateEmissionRate(address indexed user, uint256 pawPerBlock);
event SetPawTransferOwner(address indexed user, address indexed pawTransferOwner);
event TransferPawOwnership(address indexed user, address indexed newOwner);
constructor(
PawToken _paw,
uint256 _startBlock,
IRewardLocker _rewardLocker,
address _devAddress,
address _pawTransferOwner
) public {
require(_devAddress != address(0), "!nonzero");
paw = _paw;
startBlock = _startBlock;
rewardLocker = _rewardLocker;
devAddress = _devAddress;
pawTransferOwner = _pawTransferOwner;
IERC20(_paw).safeApprove(address(_rewardLocker), uint256(0));
IERC20(_paw).safeIncreaseAllowance(
address(_rewardLocker),
uint256(-1)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
mapping(IERC20 => bool) public poolExistence;
modifier nonDuplicated(IERC20 _lpToken) {
require(poolExistence[_lpToken] == false, "nonDuplicated: duplicated");
_;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _massUpdatePools) external onlyOwner nonDuplicated(_lpToken) {
require(_allocPoint <= MAX_ALLOC_POINT, "!overmax");
if (_massUpdatePools) {
massUpdatePools(); // This ensures that massUpdatePools will not exceed gas limit
}
_lpToken.balanceOf(address(this)); // Check to make sure it's a token
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolExistence[_lpToken] = true;
poolInfo.push(PoolInfo({
lpToken: _lpToken,
totalDeposited: 0,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accPawPerShare: 0
}));
emit Add(msg.sender, _allocPoint, _lpToken, _massUpdatePools);
}
// Update the given pool's PAW allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) external onlyOwner {
require(_allocPoint <= MAX_ALLOC_POINT, "!overmax");
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
emit Set(msg.sender, _pid, _allocPoint);
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from);
}
// View function to see pending PAW on frontend.
function pendingPaw(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPawPerShare = pool.accPawPerShare;
if (block.number > pool.lastRewardBlock && pool.totalDeposited != 0 && totalAllocPoint != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 pawReward = multiplier.mul(pawPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accPawPerShare = accPawPerShare.add(pawReward.mul(1e18).div(pool.totalDeposited));
}
return user.amount.mul(accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.totalDeposited == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 pawReward = multiplier.mul(pawPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
paw.mint(devAddress, pawReward.div(50)); // 2%
paw.mint(address(this), pawReward);
pool.accPawPerShare = pool.accPawPerShare.add(pawReward.mul(1e18).div(pool.totalDeposited));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for PAW allocation.
function deposit(uint256 _pid, uint256 _amount, bool _shouldHarvest) external nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
_updateUserReward(_pid, _shouldHarvest);
if (_amount > 0) {
uint256 beforeDeposit = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount);
uint256 afterDeposit = pool.lpToken.balanceOf(address(this));
_amount = afterDeposit.sub(beforeDeposit);
user.amount = user.amount.add(_amount);
pool.totalDeposited = pool.totalDeposited.add(_amount);
}
emit Deposit(msg.sender, _pid, _amount, _shouldHarvest);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount, bool _shouldHarvest) external nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
_updateUserReward(_pid, _shouldHarvest);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.totalDeposited = pool.totalDeposited.sub(_amount);
pool.lpToken.safeTransfer(msg.sender, _amount);
}
emit Withdraw(msg.sender, _pid, _amount, _shouldHarvest);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.lastPawPerShare = 0;
user.unclaimed = 0;
pool.totalDeposited = pool.totalDeposited.sub(amount);
pool.lpToken.safeTransfer(msg.sender, amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Update the rewards of caller, and harvests if needed
function _updateUserReward(uint256 _pid, bool _shouldHarvest) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount == 0) {
user.lastPawPerShare = pool.accPawPerShare;
}
uint256 pending = user.amount.mul(pool.accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed);
user.unclaimed = _shouldHarvest ? 0 : pending;
if (_shouldHarvest && pending > 0) {
_lockReward(msg.sender, pending);
emit Harvest(msg.sender, _pid, pending);
}
user.lastPawPerShare = pool.accPawPerShare;
}
// Harvest one pool
function harvest(uint256 _pid) external nonReentrant {
_updateUserReward(_pid, true);
}
// Harvest specific pools into one vest
function harvestMultiple(uint256[] calldata _pids) external nonReentrant {
uint256 pending = 0;
for (uint256 i = 0; i < _pids.length; i++) {
updatePool(_pids[i]);
PoolInfo storage pool = poolInfo[_pids[i]];
UserInfo storage user = userInfo[_pids[i]][msg.sender];
if (user.amount == 0) {
user.lastPawPerShare = pool.accPawPerShare;
}
pending = pending.add(user.amount.mul(pool.accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed));
user.unclaimed = 0;
user.lastPawPerShare = pool.accPawPerShare;
}
if (pending > 0) {
_lockReward(msg.sender, pending);
}
emit HarvestMultiple(msg.sender, _pids, pending);
}
// Harvest all into one vest. Will probably not be used
// Can fail if pool length is too big due to massUpdatePools()
function harvestAll() external nonReentrant {
massUpdatePools();
uint256 pending = 0;
for (uint256 i = 0; i < poolInfo.length; i++) {
PoolInfo storage pool = poolInfo[i];
UserInfo storage user = userInfo[i][msg.sender];
if (user.amount == 0) {
user.lastPawPerShare = pool.accPawPerShare;
}
pending = pending.add(user.amount.mul(pool.accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed));
user.unclaimed = 0;
user.lastPawPerShare = pool.accPawPerShare;
}
if (pending > 0) {
_lockReward(msg.sender, pending);
}
emit HarvestAll(msg.sender, pending);
}
/**
* @dev Call locker contract to lock rewards
*/
function _lockReward(address _account, uint256 _amount) internal {
uint256 pawBal = paw.balanceOf(address(this));
rewardLocker.lock(paw, _account, _amount > pawBal ? pawBal : _amount);
}
// Update dev address by the previous dev.
function setDevAddress(address _devAddress) external onlyOwner {
require(_devAddress != address(0), "!nonzero");
devAddress = _devAddress;
emit SetDevAddress(msg.sender, _devAddress);
}
// Should never fail as long as massUpdatePools is called during add
function updateEmissionRate(uint256 _pawPerBlock) external onlyOwner {
require(_pawPerBlock <= MAX_EMISSION_RATE, "!overmax");
massUpdatePools();
pawPerBlock = _pawPerBlock;
emit UpdateEmissionRate(msg.sender, _pawPerBlock);
}
// Update paw transfer owner. Can only be called by existing pawTransferOwner
function setPawTransferOwner(address _pawTransferOwner) external {
require(msg.sender == pawTransferOwner);
pawTransferOwner = _pawTransferOwner;
emit SetPawTransferOwner(msg.sender, _pawTransferOwner);
}
/**
* @dev DUE TO THIS CODE THIS CONTRACT MUST BE BEHIND A TIMELOCK (Ideally 7)
* THIS FUNCTION EXISTS ONLY IF THERE IS AN ISSUE WITH THIS CONTRACT
* AND TOKEN MIGRATION MUST HAPPEN
*/
function transferPawOwnership(address _newOwner) external {
require(msg.sender == pawTransferOwner);
paw.transferOwnership(_newOwner);
emit TransferPawOwnership(msg.sender, _newOwner);
}
}
| Harvest specific pools into one vest | function harvestMultiple(uint256[] calldata _pids) external nonReentrant {
uint256 pending = 0;
for (uint256 i = 0; i < _pids.length; i++) {
updatePool(_pids[i]);
PoolInfo storage pool = poolInfo[_pids[i]];
UserInfo storage user = userInfo[_pids[i]][msg.sender];
if (user.amount == 0) {
user.lastPawPerShare = pool.accPawPerShare;
}
pending = pending.add(user.amount.mul(pool.accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed));
user.unclaimed = 0;
user.lastPawPerShare = pool.accPawPerShare;
}
if (pending > 0) {
_lockReward(msg.sender, pending);
}
emit HarvestMultiple(msg.sender, _pids, pending);
}
| 901,541 | [
1,
44,
297,
26923,
2923,
16000,
1368,
1245,
331,
395,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
17895,
26923,
8438,
12,
11890,
5034,
8526,
745,
892,
389,
84,
2232,
13,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2254,
5034,
4634,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
84,
2232,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1089,
2864,
24899,
84,
2232,
63,
77,
19226,
203,
5411,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
84,
2232,
63,
77,
13563,
31,
203,
5411,
25003,
2502,
729,
273,
16753,
63,
67,
84,
2232,
63,
77,
65,
6362,
3576,
18,
15330,
15533,
203,
5411,
309,
261,
1355,
18,
8949,
422,
374,
13,
288,
203,
7734,
729,
18,
2722,
52,
2219,
2173,
9535,
273,
2845,
18,
8981,
52,
2219,
2173,
9535,
31,
203,
5411,
289,
203,
5411,
4634,
273,
4634,
18,
1289,
12,
1355,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
52,
2219,
2173,
9535,
18,
1717,
12,
1355,
18,
2722,
52,
2219,
2173,
9535,
13,
2934,
2892,
12,
21,
73,
2643,
2934,
1289,
12,
1355,
18,
551,
80,
4581,
329,
10019,
203,
5411,
729,
18,
551,
80,
4581,
329,
273,
374,
31,
203,
5411,
729,
18,
2722,
52,
2219,
2173,
9535,
273,
2845,
18,
8981,
52,
2219,
2173,
9535,
31,
203,
3639,
289,
203,
3639,
309,
261,
9561,
405,
374,
13,
288,
203,
5411,
389,
739,
17631,
1060,
12,
3576,
18,
15330,
16,
4634,
1769,
203,
3639,
289,
203,
3639,
3626,
670,
297,
26923,
8438,
12,
3576,
18,
15330,
16,
389,
84,
2232,
16,
4634,
1769,
203,
565,
289,
2
] |
// THIS CONTRACT IS UNSAFE because I added two major bugs to make it more
// exciting to audit ;)
// One bug is easy to spot, and the other is more subtle. The more subtle bug
// may or may not be dangerous. But the other is definitely bad. Hint: don't
// even trust the comments ;)
pragma solidity 0.4.18;
import "zeppelin-solidity/contracts/math/SafeMath.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
contract BuggyContract is Ownable {
//// Data types:
struct Gift {
bool exists; // 0 Only true if this exists
uint giftId; // 1 The gift ID
address giver; // 2 The address of the giver
address recipient; // 3 The address of the recipient
uint expiry; // 4 The expiry datetime of the timelock as a
// Unix timestamp
uint amount; // 5 The amount of ETH
bool redeemed; // 6 Whether the funds have already been redeemed
bool returned; // 7 Whether the funds were returned to the giver
bool refunded; // 8 Whether the funds were refunded to the giver
}
//// Mappings and state variables:
// Total fees collected
uint public feesCollected;
// Each gift has a unique ID. If you increment this value, you should get
// an unused gift ID.
uint public nextGiftId;
// Whether refunds are allowed. Set this to true using allowRefunds() only
// in an emergency. If refundsAllowed is true, claimRefund() will allow a
// refund to go through.
bool private refundsAllowed;
// recipientToGiftIds maps each recipient address to a list of giftIDs of
// Gifts they have received.
mapping (address => uint[]) public recipientToGiftIds;
// giftIdToGift maps each gift ID to its associated gift.
mapping (uint => Gift) public giftIdToGift;
//// Events:
event Constructed (address indexed by, uint indexed amount);
event DirectlyDeposited(address indexed from, uint indexed amount);
event Gave (uint indexed giftId,
address indexed giver,
address indexed recipient,
uint amount, uint expiry);
event Redeemed (uint indexed giftId,
address indexed giver,
address indexed recipient,
uint amount);
event CollectedAllFees (address indexed by, uint indexed amount);
event ReturnedToGiver (uint indexed giftId);
event ChangedRecipient (uint indexed giftId,
address indexed originalRecipient,
address indexed newRecipient);
event ClaimedRefund(address by, uint indexed amount, uint indexed giftId);
event AllowedRefunds(address indexed by);
event DisallowedRefunds(address indexed by);
// Constructor
function BuggyContract() public payable {
refundsAllowed = false; // disallow refunds by default
Constructed(msg.sender, msg.value);
}
// Fallback function which allows this contract to receive funds.
function () public payable {
// Sending ETH directly to this contract does nothing except log an
// event.
DirectlyDeposited(msg.sender, msg.value);
}
//// Getter functions:
function getFeesCollected () public onlyOwner view returns (uint) {
return feesCollected;
}
function doesGiftExist (uint giftId) public view returns (bool) {
return giftIdToGift[giftId].exists;
}
function getGiftGiver (uint giftId) public view returns (address) {
return giftIdToGift[giftId].giver;
}
function getGiftRecipient (uint giftId) public view returns (address) {
return giftIdToGift[giftId].recipient;
}
function getGiftAmount (uint giftId) public view returns (uint) {
return giftIdToGift[giftId].amount;
}
function getGiftExpiry (uint giftId) public view returns (uint) {
return giftIdToGift[giftId].expiry;
}
function isGiftRedeemed (uint giftId) public view returns (bool) {
return giftIdToGift[giftId].redeemed;
}
function isGiftReturned (uint giftId) public view returns (bool) {
return giftIdToGift[giftId].returned;
}
function isGiftRefunded (uint giftId) public view returns (bool) {
return giftIdToGift[giftId].refunded;
}
function getGiftIdsByRecipient (address recipient)
public view returns (uint[]) {
return recipientToGiftIds[recipient];
}
//// Contract functions:
// Call this function while sending ETH to give a gift.
// @recipient: the recipient's address
// @expiry: the Unix timestamp of the expiry datetime.
// Tested in test/test_give.js and test/TestGive.sol
function give (address recipient, uint expiry) public payable returns (uint) {
address giver = msg.sender;
// Validate the giver address
assert(giver != address(0));
// The gift must be a positive amount of ETH
uint amount = msg.value;
require(amount > 0);
// The expiry datetime must be in the future. It is fine to use the
// block timestamp in this contract because the possible drift is
// only 12 minutes. See: https://consensys.github.io
// /smart-contract-best-practices/recommendations/#timestamp-dependence
require(expiry > now);
// The giver and the recipient must be different addresses
require(giver != recipient);
// The recipient must be a valid address
require(recipient != address(0));
// Make sure nextGiftId is 0 or positive, or this contract is buggy
assert(nextGiftId >= 0);
// Append the gift to the mapping
recipientToGiftIds[recipient].push(nextGiftId);
// Calculate the contract owner's fee
uint feeTaken = fee(amount);
assert(feeTaken >= 0);
// Increment feesCollected
feesCollected = SafeMath.add(feesCollected, feeTaken);
// Shave off the fee
uint amtGiven = SafeMath.sub(amount, feeTaken);
assert(amtGiven > 0);
// If a gift with this new gift ID already exists, this contract is buggy.
assert(giftIdToGift[nextGiftId].exists == false);
// Update the giftIdToGift mapping with the new gift
giftIdToGift[nextGiftId] =
Gift(true, nextGiftId, giver, recipient, expiry, amtGiven,
false, false, false);
uint giftId = nextGiftId;
// Increment nextGiftId
nextGiftId = SafeMath.add(giftId, 1);
// If a gift with this new gift ID already exists, this contract is buggy.
assert(giftIdToGift[nextGiftId].exists == false);
// Log the event
Gave(giftId, giver, recipient, amount, expiry);
return giftId;
}
// Call this function to redeem a gift of ETH.
// Tested in test/test_redeem.js
function redeem (uint giftId, uint amount) public {
// The giftID should be 0 or positive
require(giftId >= 0);
// The gift must exist
require(giftIdToGift[giftId].exists == true);
// The gift must exist and must not have already been redeemed, returned, or refunded
require(isValidGift(giftIdToGift[giftId]));
// The recipient must be the caller of this function
address recipient = giftIdToGift[giftId].recipient;
require(recipient == msg.sender);
// The current datetime must be after the expiry datetime
require(now > giftIdToGift[giftId].expiry);
//// If the following assert statements are triggered, this contract is
//// buggy.
// The amount must be positive because this is required in give()
assert(amount > 0);
// The giver must not be the recipient because this was asserted in give()
address giver = giftIdToGift[giftId].giver;
assert(giver != recipient);
// Make sure the giver is valid because this was asserted in give();
assert(giver != address(0));
// Update the gift to mark it as redeemed, so that the funds cannot be
// double-spent
giftIdToGift[giftId].redeemed = true;
// Transfer the funds
recipient.transfer(amount);
// Log the event
Redeemed(giftId, giftIdToGift[giftId].giver, recipient, amount);
}
// Calculate the contract owner's fee
// Tested in test/test_fee.js
function fee (uint amount) public pure returns (uint) {
if (amount < 0.01 ether) {
return 0;
} else if (amount >= 0.01 ether && amount < 0.1 ether) {
return SafeMath.div(amount, 100000);
} else if (amount >= 0.1 ether && amount < 1 ether) {
return SafeMath.div(amount, 10000);
} else if (amount >= 1 ether) {
return SafeMath.div(amount, 1000);
}
}
// Transfer the fees collected thus far to the contract owner.
// Only the contract owner may invoke this function.
// Tested in test/test_collect_fees.js
function collectAllFees () public onlyOwner {
// Store the fee amount in a temporary variable
uint amount = feesCollected;
// Make sure that the amount is positive
require(amount > 0);
// Set the feesCollected state variable to 0
feesCollected = 0;
// Make the transfer
owner.transfer(amount);
CollectedAllFees(owner, amount);
}
// A recipient may change the recipient address of a Gift
// Tested in test/test_change_recipient.js and test_update_recipient_to_giftids.js
function changeRecipient (address newRecipient, uint giftId) public {
// Validate the giftId
require(giftId >= 0);
// Validate the new recipient address
require(newRecipient != address(0));
// The gift must exist and must not have already been redeemed, returned, or refunded
require(isValidGift(giftIdToGift[giftId]));
// Only allow an the existing recipient of the gift with giftId to
// change the recipient
address currentRecipient = giftIdToGift[giftId].recipient;
require(msg.sender == currentRecipient);
// The giver must not be the recipient because this is required in give() and redeem()
address giver = giftIdToGift[giftId].giver;
require(giver != newRecipient);
// Make sure the new recipient is not the same as the existing one
require(currentRecipient != newRecipient);
// Update the gift
giftIdToGift[giftId].recipient = newRecipient;
// Make sure that the exisiting recipient is in the recipientToGiftIds mapping
require(recipientToGiftIds[msg.sender].length > 0);
// Update the recipientToGiftIds mapping. This is slightly tricky.
// First, remove the gift from the mapping for the old recipient.
// If the giftId is the last element of the array, deleting it is
// straightforward:
uint len = recipientToGiftIds[msg.sender].length;
bool success = false;
if (recipientToGiftIds[msg.sender][len-1] == giftId) {
// Just delete the last element
delete recipientToGiftIds[msg.sender][len-1];
// Decrement the array length
recipientToGiftIds[msg.sender].length--;
// For the assert stmt later on
success = true;
} else {
// Otherwise, find its index (i), replace it with the last element, and
// then delete the last element
for (uint i=0; i < len-1; i++) {
if (recipientToGiftIds[msg.sender][i] == giftId) {
// Replace the found item at [i] with the last element
uint lastGiftId = recipientToGiftIds[msg.sender][len-1];
recipientToGiftIds[msg.sender][i] = lastGiftId;
// For the assert stmt later on
success = true;
break;
}
}
}
// Make sure the removal worked and make sure the array length is
// smaller by 1
assert(success == true);
assert(len-1 == recipientToGiftIds[msg.sender].length);
// Finally, append the giftId to the array in the mapping for the new recipient
recipientToGiftIds[newRecipient].push(giftId);
// Log the event
ChangedRecipient(giftId, msg.sender, newRecipient);
}
// A recipient may choose to return the funds to the giver at any time
// Tested by test/test_return_to_giver.js
function returnToGiver (uint giftId) public {
// Validate the giftId
require(giftId >= 0);
// The gift must exist and must not have already been redeemed, returned, or refunded
require(isValidGift(giftIdToGift[giftId]));
// Only the recipient can return funds to the giver
require(giftIdToGift[giftId].recipient == msg.sender);
// Only allow a positive fund transfer
require(giftIdToGift[giftId].amount > 0);
// Make sure the giver's address is valid as this is asserted in give() and redeem():
assert(giftIdToGift[giftId].giver != address(0));
// Update the gift data
giftIdToGift[giftId].returned = true;
// Make the transfer
giftIdToGift[giftId].giver.transfer(giftIdToGift[giftId].amount);
// Log the event
ReturnedToGiver(giftId);
}
// This function should only be called in the unlikey situation where the
// funds have to be returned to all givers. Refunds are only possible if
// the expiry datetime has not passed.
// Tested by test/test_refund.js
function claimRefund(uint giftId) public {
// Only allow a refund if allowRefunds() has been invoked
require(refundsAllowed == true);
// The gift must exist and must not have already been redeemed, returned, or refunded
require(isValidGift(giftIdToGift[giftId]));
// Only the gift giver can call this function
address giver = giftIdToGift[giftId].giver;
require(giver == msg.sender);
// Make sure the giver's address is valid as this is asserted in give() and redeem():
assert(giftIdToGift[giftId].giver != address(0));
// Only transfer positive amounts
uint amount = giftIdToGift[giftId].amount;
require(amount > 0);
// Only allow refunds before the expiry
require(giftIdToGift[giftId].expiry > now);
// Mark the gift as refunded
giftIdToGift[giftId].refunded = true;
// Make the transfer
giver.transfer(amount);
// Log this event
ClaimedRefund(giver, amount, giftId);
}
// Only call this in the event that givers should be allowed to get their funds back
function allowRefunds () public onlyOwner {
refundsAllowed = true;
AllowedRefunds(owner); // Log the event
}
// Reverse allowRefunds()
function disallowRefunds () public onlyOwner {
refundsAllowed = false;
DisallowedRefunds(owner); // Log the event
}
// Returns true only if the gift exists and has not already been
// redeemed, returned, or refunded
function isValidGift(Gift gift) private pure returns (bool) {
return gift.exists == true &&
gift.redeemed == false &&
gift.returned == false &&
gift.refunded == false;
}
}
| 8 Whether the funds were refunded to the giver
| bool refunded; | 12,588,801 | [
1,
28,
17403,
326,
284,
19156,
4591,
1278,
12254,
358,
326,
314,
1667,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1426,
1278,
12254,
31,
4202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-02
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
pragma experimental ABIEncoderV2;
/*
* @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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title 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 Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address Serial
*/
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
* Serials of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {size := extcodesize(account)}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value : value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev 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);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
}
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error AuxQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Base URI
string private _baseURI;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 1;
}
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI_ = baseURI();
return bytes(baseURI_).length != 0 ? string(abi.encodePacked(baseURI_, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function baseURI() internal view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
}
while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
/**
* @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;
}
}
abstract contract OwnerCheck is Ownable {
mapping(address => bool) public keeperMap;
uint8 private unlocked = 1;
event SetKeeper(address addr, bool auth);
modifier onlyKeeper(address addr) {
require(isKeeper(addr), "caller is not the keeper");
_;
}
modifier lock() {
require(unlocked == 1, 'Contract: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function setKeeper(address addr, bool auth) public onlyOwner {
keeperMap[addr] = auth;
emit SetKeeper(addr, auth);
}
function isKeeper(address addr) public view returns (bool) {
return keeperMap[addr];
}
}
interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
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 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");
}
}
}
contract MNSNFT is ERC721A, OwnerCheck {
using SafeMath for uint256;
using Strings for uint256;
using SafeERC20 for IERC20;
IERC20 public metaToken;
//card id start from 1
//nick name=>card id
mapping(bytes32 => uint256) private nickNameCardId;
//keep lower nick name=>card id for check if nick name already register
mapping(bytes32 => uint256) private nickNameLowerCardId;
//card id=>nick name
mapping(uint256 => bytes32) private cardIdNickName;
//user address=>current nick name used in metalk
mapping(address => bytes32) private userBindNickName;
//price of one nick name
uint256 public nickNamePrice = 5e16;
uint256 public nickNameMetaPrice;
address payable public ethRecipient = payable(0x50884B6452D807576a4B316DDE1944F0B66069A7);
bool public useWhiteList = true;
bool public metaUseWhiteList = true;
//white list merkle root
bytes32 public merkleRoot = 0x4660af648282e8881b4beb703d11d5ef2646a5ccc8b8e46e649f3790f6954e39;
bytes32 public metaMerkleRoot;
//already minted number less than max amount in white list
//0-10 is which type mint,0 value means not mint;1 means already mint
//16- save already minted
//Cryptopunk=1、Meebits=2、Clonex=3、VeeFriends=4、AZUKI=5
//BAYC=6、MAYC=7、Doodle=8、InvisibleFriends=9、Mfers=10
//0 for others
mapping(address => uint256) private _alreadyMinted;
mapping(address => uint256) private _metaAlreadyMinted;
bool public stopped = true;
bool public metaStopped = true;
struct social {
string twitter;
string instagram;
string facebook;
string discord;
}
mapping(address => social) socialLink;
event BuyNickName(address user, bytes32 nickName, uint256 cardId, uint256 nickNamePrice, uint8 _type);
event BuyNickNameByMeta(address user, bytes32 nickName, uint256 cardId, uint256 nickNamePrice, uint8 _type);
event ChangeBindMNS(address user, uint256 cardId, bytes32 currentNick, bytes32 nick);
//just for get function,not store data
struct tokenNickName {
uint256 tokenId;
string nickName;
string uri;
}
constructor(string memory _name, string memory _symbol, IERC20 meta) ERC721A(_name, _symbol) {
_setBaseURI("https://storage.googleapis.com/metalk/mns/metadata/");
metaToken = meta;
}
function buy(bytes32 _nickName, bytes32[] calldata merkleProof, uint64 maxCount, uint8 _type) public payable lock {
require(!stopped, 'stopped');
require(msg.value == nickNamePrice, 'eth need more');
(bytes32 lo,bool valid) = lower(_nickName);
require(valid, 'name invalid');
require(nickNameLowerCardId[lo] == 0, 'name exists');
if (useWhiteList) {
require((_type > 0) && (_type < 11), 'type wrong');
uint256 temp = _alreadyMinted[msg.sender];
(uint64 total, uint16 setValue) = (uint64(temp >> 16), uint16(temp) & (uint16(0x01) << _type));
require(total < uint64(maxCount), 'Insufficient left');
require(setValue == 0, 'type used');
require(_verify(merkleProof, msg.sender, uint256(maxCount), merkleRoot), 'Invalid proof');
_alreadyMinted[msg.sender] = uint256(uint256(total + 1) << 16) | uint256((uint16(temp) | (uint16(0x01) << _type)));
}
ethRecipient.transfer(nickNamePrice);
uint256 cardId = mint(msg.sender, _nickName, lo);
emit BuyNickName(msg.sender, _nickName, cardId, nickNamePrice, _type);
}
//approve meta first
function buyUseMeta(bytes32 _nickName, bytes32[] calldata merkleProof, uint64 maxCount, uint8 _type) public payable lock {
require(!metaStopped, 'stopped');
(bytes32 lo,bool valid) = lower(_nickName);
require(valid, 'name invalid');
require(nickNameLowerCardId[lo] == 0, 'name exists');
if (metaUseWhiteList) {
require((_type > 0) && (_type < 11), 'type wrong');
uint256 temp = _metaAlreadyMinted[msg.sender];
(uint64 total, uint16 setValue) = (uint64(temp >> 16), uint16(temp) & (uint16(0x01) << _type));
require(setValue == 0, 'type used');
require(total < uint256(maxCount), 'Insufficient meta left');
require(_verify(merkleProof, msg.sender, uint256(maxCount), metaMerkleRoot), 'Invalid proof');
_metaAlreadyMinted[msg.sender] = uint256(uint256(total + 1) << 16) | uint256((uint16(temp) | (uint16(0x01) << _type)));
}
metaToken.safeTransferFrom(msg.sender, ethRecipient, nickNameMetaPrice);
uint256 cardId = mint(msg.sender, _nickName, lo);
emit BuyNickNameByMeta(msg.sender, _nickName, cardId, nickNameMetaPrice, _type);
}
function mint(address to, bytes32 _nickName, bytes32 lo) private returns (uint cardId){
//card id start from 1
cardId = totalSupply() + 1;
_mint(to, 1, new bytes(0), false);
(nickNameCardId[_nickName], nickNameLowerCardId[lo], cardIdNickName[cardId]) = (cardId, cardId, _nickName);
}
function _verify(
bytes32[] calldata merkleProof,
address sender,
uint256 maxAmount,
bytes32 _merkleRoot
) private pure returns (bool) {
bytes32 leaf = keccak256(abi.encodePacked(sender, maxAmount.toString()));
return processProof(merkleProof, leaf) == _merkleRoot;
}
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
function changeBindMNS(uint256 cardId) public lock {
address owner = ownerOf(cardId);
require(msg.sender == owner, "not owner");
emit ChangeBindMNS(msg.sender, cardId, userBindNickName[msg.sender], cardIdNickName[cardId]);
userBindNickName[msg.sender] = cardIdNickName[cardId];
}
//for user unbind card and sell
function clearBindMNS() public lock {
bytes32 oldNickName = userBindNickName[msg.sender];
require(oldNickName != 0, "not bind");
uint256 cardId = nickNameCardId[oldNickName];
address owner = ownerOf(cardId);
require(msg.sender == owner, "not owner");
emit ChangeBindMNS(msg.sender, cardId, oldNickName, 0);
delete userBindNickName[msg.sender];
}
function _beforeTokenTransfers(
address from,
address,
uint256 startTokenId,
uint256 quantity) internal override {
bytes32 currentNickName = userBindNickName[from];
if (currentNickName != 0) {
for (uint i = 0; i < quantity; i++) {
if (nickNameCardId[currentNickName] == startTokenId + i) {
emit ChangeBindMNS(from, startTokenId + i, currentNickName, 0);
delete userBindNickName[from];
break;
}
}
}
}
function userBindInfo(address[] memory user) external view returns (tokenNickName[] memory ret){
uint256 count = user.length;
ret = new tokenNickName[](count);
for (uint256 i = 0; i < count; i++) {
ret[i].nickName = bytes32ToString(userBindNickName[user[i]]);
if (userBindNickName[user[i]] != 0) {
ret[i].tokenId = nickNameCardId[userBindNickName[user[i]]];
ret[i].uri = tokenURI(ret[i].tokenId);
}
}
}
function tokenOf(uint256[] memory tokenIds) external view returns (tokenNickName[] memory ret){
ret = new tokenNickName[](tokenIds.length);
for (uint256 i = 0; i < tokenIds.length; i++) {
ret[i].tokenId = tokenIds[i];
ret[i].nickName = bytes32ToString(cardIdNickName[tokenIds[i]]);
ret[i].uri = tokenURI(tokenIds[i]);
}
}
function bindTwitterByUser(string memory twitter) public {
socialLink[msg.sender].twitter = twitter;
}
function bindInstagramByUser(string memory instagram) public {
socialLink[msg.sender].instagram = instagram;
}
function bindFacebookByUser(string memory facebook) public {
socialLink[msg.sender].facebook = facebook;
}
function bindDiscordByUser(string memory discord) public {
socialLink[msg.sender].discord = discord;
}
function getSocial(address user) public view returns (social memory){
return socialLink[user];
}
function getNickNameCardId(bytes32 nick) public view returns (uint256){
return nickNameCardId[nick];
}
function getNickNameExist(bytes32 nick) public view returns (bool){
return nickNameLowerCardId[nick] != 0;
}
function getCardIdNickName(uint256 cardId) public view returns (string memory){
return bytes32ToString(cardIdNickName[cardId]);
}
function getUserBindNickName(address user) public view returns (string memory){
return bytes32ToString(userBindNickName[user]);
}
function getUserAddress(bytes32 nick) public view returns (address ret){
uint256 card = nickNameCardId[nick];
if (card != 0) {
ret = ownerOf(card);
}
}
//set base uri
function setBaseTokenURI(string memory baseTokenURI) external onlyOwner {
_setBaseURI(baseTokenURI);
}
function getBaseURI() public view returns (string memory){
return baseURI();
}
function setNickNamePrice(uint256 _nickNamePrice) public onlyOwner {
nickNamePrice = _nickNamePrice;
}
function setNickNameMetaPrice(uint256 price) public onlyOwner {
nickNameMetaPrice = price;
}
function setEthRecipient(address payable _ethRecipient) public onlyOwner {
ethRecipient = _ethRecipient;
}
function bytes32ToString(bytes32 input) private pure returns (string memory){
if (input == 0) {
return "";
}
uint8 i = 0;
while (i < 32 && input[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && input[i] != 0; i++) {
bytesArray[i] = input[i];
}
return string(bytesArray);
}
function lower(bytes32 _nickName) private pure returns (bytes32 ret, bool valid){
if (_nickName == 0) {
return (ret, false);
}
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytes1 nick = _nickName[i];
if (nick == 0) {
break;
} else if (nick >= bytes1("A") && nick <= bytes1("Z")) {
bytesArray[i] = bytes1(uint8(nick) + 32);
} else if ((nick >= bytes1("0") && nick <= bytes1("9")) || (nick >= bytes1("a") && nick <= bytes1("z"))) {
bytesArray[i] = _nickName[i];
} else {
return (ret, false);
}
}
ret = bytes32(bytesArray);
valid = true;
}
function setUseWhiteList(bool use) public onlyOwner {
useWhiteList = use;
}
function setUseMetaWhiteList(bool use) public onlyOwner {
metaUseWhiteList = use;
}
function setMerkleProof(bytes32 _merkleRoot) public onlyOwner {
merkleRoot = _merkleRoot;
}
function setMetaMerkleProof(bytes32 _merkleRoot) public onlyOwner {
metaMerkleRoot = _merkleRoot;
}
//index 0 is total minted
function getAlreadyMinted(address addr) public view returns (uint64 total, uint8[11] memory typeCount) {
total = uint64(_alreadyMinted[addr] >> 16);
for (uint i = 0; i < 11; i++) {
typeCount[i] = uint8((uint16(_alreadyMinted[addr]) & 2 ** i) >> i);
}
}
function getMetaAlreadyMinted(address addr) public view returns (uint64 metaTotal, uint8[11] memory metaTypeCount) {
metaTotal = uint64(_metaAlreadyMinted[addr] >> 16);
for (uint i = 0; i < 11; i++) {
metaTypeCount[i] = uint8((uint16(_metaAlreadyMinted[addr]) & 2 ** i) >> i);
}
}
function setStopped(bool flag) public onlyOwner {
stopped = flag;
}
function setUseMetaStopped(bool flag) public onlyOwner {
metaStopped = flag;
}
} | index 0 is total minted | function getAlreadyMinted(address addr) public view returns (uint64 total, uint8[11] memory typeCount) {
total = uint64(_alreadyMinted[addr] >> 16);
for (uint i = 0; i < 11; i++) {
typeCount[i] = uint8((uint16(_alreadyMinted[addr]) & 2 ** i) >> i);
}
}
| 2,299,884 | [
1,
1615,
374,
353,
2078,
312,
474,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
9430,
49,
474,
329,
12,
2867,
3091,
13,
1071,
1476,
1135,
261,
11890,
1105,
2078,
16,
2254,
28,
63,
2499,
65,
3778,
618,
1380,
13,
288,
203,
3639,
2078,
273,
2254,
1105,
24899,
17583,
49,
474,
329,
63,
4793,
65,
1671,
2872,
1769,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
4648,
31,
277,
27245,
288,
203,
5411,
618,
1380,
63,
77,
65,
273,
2254,
28,
12443,
11890,
2313,
24899,
17583,
49,
474,
329,
63,
4793,
5717,
473,
576,
2826,
277,
13,
1671,
277,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
___ _ ___ _
| .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___
| _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._>
|_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___.
* PeriFinance: PeriFinance.sol
*
* Latest source (may be newer): https://github.com/PeriFinance/periFinance/blob/master/contracts/PeriFinance.sol
* Docs: Will be added in the future. /contracts/PeriFinance
*
* Contract Dependencies:
* - BasePeriFinance
* - ExternStateToken
* - IAddressResolver
* - IERC20
* - IPeriFinance
* - MixinResolver
* - Owned
* - Proxyable
* - State
* Libraries:
* - SafeDecimalMath
* - SafeMath
* - VestingEntries
*
* MIT License
* ===========
*
* Copyright (c) 2021 PeriFinance
*
* 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
*/
pragma solidity >=0.4.24;
// https://docs.peri.finance/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.peri.finance/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/proxy
contract Proxy is Owned {
Proxyable public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(Proxyable _target) external onlyOwner {
target = _target;
emit TargetUpdated(_target);
}
function _emit(
bytes calldata callData,
uint numTopics,
bytes32 topic1,
bytes32 topic2,
bytes32 topic3,
bytes32 topic4
) external onlyTarget {
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
// solhint-disable no-complex-fallback
function() external payable {
// Mutable call setting Proxyable.messageSender as this is using call not delegatecall
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) {
revert(free_ptr, returndatasize)
}
return(free_ptr, returndatasize)
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/proxyable
contract Proxyable is Owned {
// This contract should be treated like an abstract contract
/* The proxy this contract exists behind. */
Proxy public proxy;
Proxy public integrationProxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address public messageSender;
constructor(address payable _proxy) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address payable _proxy) external onlyOwner {
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setIntegrationProxy(address payable _integrationProxy) external onlyOwner {
integrationProxy = Proxy(_integrationProxy);
}
function setMessageSender(address sender) external onlyProxy {
messageSender = sender;
}
modifier onlyProxy {
_onlyProxy();
_;
}
function _onlyProxy() private view {
require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call");
}
modifier optionalProxy {
_optionalProxy();
_;
}
function _optionalProxy() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
}
modifier optionalProxy_onlyOwner {
_optionalProxy_onlyOwner();
_;
}
// solhint-disable-next-line func-name-mixedcase
function _optionalProxy_onlyOwner() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
require(messageSender == owner, "Owner only function");
}
event ProxyUpdated(address proxyAddress);
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.peri.finance/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
// Inheritance
// https://docs.peri.finance/contracts/source/contracts/state
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _associatedContract) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract {
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
// Inheritance
// https://docs.peri.finance/contracts/source/contracts/tokenstate
contract TokenState is Owned, State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(
address tokenOwner,
address spender,
uint value
) external onlyAssociatedContract {
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value) external onlyAssociatedContract {
balanceOf[account] = value;
}
}
// Inheritance
// Libraries
// Internal references
// https://docs.peri.finance/contracts/source/contracts/externstatetoken
contract ExternStateToken is Owned, Proxyable {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields. */
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _name,
string memory _symbol,
uint _totalSupply,
uint8 _decimals,
address _owner
) public Owned(_owner) Proxyable(_proxy) {
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender) public view returns (uint) {
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account) external view returns (uint) {
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
tokenState = _tokenState;
emitTokenStateUpdated(address(_tokenState));
}
function _internalTransfer(
address from,
address to,
uint value
) internal returns (bool) {
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address");
// Insufficient balance will be handled by the safe subtraction.
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transferByProxy(
address from,
address to,
uint value
) internal returns (bool) {
return _internalTransfer(from, to, value);
}
/*
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFromByProxy(
address sender,
address from,
address to,
uint value
) internal returns (bool) {
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value) public optionalProxy returns (bool) {
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
function addressToBytes32(address input) internal pure returns (bytes32) {
return bytes32(uint256(uint160(input)));
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(
address from,
address to,
uint value
) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(
address owner,
address spender,
uint value
) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
// https://docs.peri.finance/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getPynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.peri.finance/contracts/source/interfaces/ipynth
interface IPynth {
// Views
function currencyKey() external view returns (bytes32);
function transferablePynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to PeriFinance
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function canBurnPynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to PeriFinance
function issuePynths(address from, uint amount) external;
function issuePynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxPynths(address from) external;
function issueMaxPynthsOnBehalf(address issueFor, address from) external;
function stakeUSDCAndIssuePynths(
address from,
uint usdcStakeAmount,
uint issueAmount
) external;
function stakeUSDCAndIssueMaxPynths(address from, uint usdcStakeAmount) external;
function burnPynths(address from, uint amount) external;
function burnPynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnPynthsToTarget(address from) external;
function burnPynthsToTargetOnBehalf(address burnForAddress, address from) external;
function unstakeUSDCAndBurnPynths(
address from,
uint usdcUnstakeAmount,
uint burnAmount
) external;
function unstakeUSDCToMaxAndBurnPynths(address from, uint burnAmount) external;
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getPynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.pynths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.peri.finance/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
interface IVirtualPynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function pynth() external view returns (IPynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iperiFinance
interface IPeriFinance {
// Views
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint);
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
function maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey) external view returns (uint);
function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint);
function transferablePeriFinance(address account) external view returns (uint transferable);
// Mutative Functions
function burnPynths(uint amount) external;
function burnPynthsOnBehalf(address burnForAddress, uint amount) external;
function burnPynthsToTarget() external;
function burnPynthsToTargetOnBehalf(address burnForAddress) external;
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth);
function issueMaxPynths() external;
function issuePynths(uint amount) external;
function issuePynthsOnBehalf(address issueForAddress, uint amount) external;
function issueMaxPynthsOnBehalf(address issueForAddress) external;
function stakeUSDCAndIssuePynths(uint usdcStakeAmount, uint issueAmount) external;
function stakeUSDCAndIssueMaxPynths(uint usdcStakingAmount) external;
function unstakeUSDCAndBurnPynths(uint usdcUnstakeAmount, uint burnAmount) external;
function unstakeUSDCToMaxAndBurnPynths(uint burnAmount) external;
function mint() external returns (bool);
function settle(bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
// Liquidations
function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool);
// Restricted Functions
function mintSecondary(address account, uint amount) external;
function mintSecondaryRewards(uint amount) external;
function burnSecondary(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iperiFinancestate
interface IPeriFinanceState {
// Views
function debtLedger(uint index) external view returns (uint);
function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex);
function debtLedgerLength() external view returns (uint);
function hasIssued(address account) external view returns (bool);
function lastDebtLedgerEntry() external view returns (uint);
// Mutative functions
function incrementTotalIssuerCount() external;
function decrementTotalIssuerCount() external;
function setCurrentIssuanceData(address account, uint initialDebtOwnership) external;
function appendDebtLedgerValue(uint value) external;
function clearIssuanceData(address account) external;
// Views
function periDebtLedger(uint index) external view returns (uint);
function periIssuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex);
function periDebtLedgerLength() external view returns (uint);
function hasPeriIssued(address account) external view returns (bool);
function lastPeriDebtLedgerEntry() external view returns (uint);
// Mutative functions
function incrementTotalPeriIssuerCount() external;
function decrementTotalPeriIssuerCount() external;
function setCurrentPeriIssuanceData(address account, uint initialDebtOwnership) external;
function appendPeriDebtLedgerValue(uint value) external;
function clearPeriIssuanceData(address account) external;
}
// https://docs.peri.finance/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requirePynthActive(bytes32 currencyKey) external view;
function requirePynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function pynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function pynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getPynthExchangeSuspensions(bytes32[] calldata pynths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getPynthSuspensions(bytes32[] calldata pynths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendPynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isPynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function setLastExchangeRateForPynth(bytes32 currencyKey, uint rate) external;
function suspendPynthWithInvalidRate(bytes32 currencyKey) external;
}
// https://docs.peri.finance/contracts/source/interfaces/irewardsdistribution
interface IRewardsDistribution {
// Structs
struct DistributionData {
address destination;
uint amount;
}
// Views
function authority() external view returns (address);
function distributions(uint index) external view returns (address destination, uint amount); // DistributionData
function distributionsLength() external view returns (uint);
// Mutative Functions
function distributeRewards(uint amount) external returns (bool);
}
// Inheritance
// Libraries
// Internal references
contract BasePeriFinance is IERC20, ExternStateToken, MixinResolver, IPeriFinance {
using SafeMath for uint;
using SafeDecimalMath for uint;
// ========== STATE VARIABLES ==========
struct LockState {
address account;
uint startTime;
uint iterations;
uint totalAmount;
uint unitTime;
uint endTime;
}
// Available Pynths which can be used with the system
string public constant TOKEN_NAME = "Peri Finance Token";
string public constant TOKEN_SYMBOL = "PERI";
uint8 public constant DECIMALS = 18;
bytes32 public constant pUSD = "pUSD";
mapping(address => LockState) public lockStates;
event LockChanged(
address indexed account,
uint startTime,
uint iterations,
uint totalAmount,
uint unitTime,
uint endTime
);
// ========== ADDRESS RESOLVER CONFIGURATION ==========
bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState";
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
// ========== CONSTRUCTOR ==========
constructor(
address payable _proxy,
TokenState _tokenState,
address _owner,
uint _totalSupply,
address _resolver
)
public
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner)
MixinResolver(_resolver)
{}
// ========== VIEWS ==========
// Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](5);
addresses[0] = CONTRACT_PERIFINANCESTATE;
addresses[1] = CONTRACT_SYSTEMSTATUS;
addresses[2] = CONTRACT_EXCHANGER;
addresses[3] = CONTRACT_ISSUER;
addresses[4] = CONTRACT_REWARDSDISTRIBUTION;
}
function periFinanceState() internal view returns (IPeriFinanceState) {
return IPeriFinanceState(requireAndGetAddress(CONTRACT_PERIFINANCESTATE));
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function rewardsDistribution() internal view returns (IRewardsDistribution) {
return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION));
}
function debtBalanceOf(address account, bytes32 currencyKey) external view returns (uint) {
return issuer().debtBalanceOf(account, currencyKey);
}
function totalIssuedPynths(bytes32 currencyKey) external view returns (uint) {
return issuer().totalIssuedPynths(currencyKey, false);
}
function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint) {
return issuer().totalIssuedPynths(currencyKey, true);
}
function availableCurrencyKeys() external view returns (bytes32[] memory) {
return issuer().availableCurrencyKeys();
}
function availablePynthCount() external view returns (uint) {
return issuer().availablePynthCount();
}
function availablePynths(uint index) external view returns (IPynth) {
return issuer().availablePynths(index);
}
function pynths(bytes32 currencyKey) external view returns (IPynth) {
return issuer().pynths(currencyKey);
}
function pynthsByAddress(address pynthAddress) external view returns (bytes32) {
return issuer().pynthsByAddress(pynthAddress);
}
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool) {
return exchanger().maxSecsLeftInWaitingPeriod(messageSender, currencyKey) > 0;
}
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) {
return issuer().anyPynthOrPERIRateIsInvalid();
}
function maxIssuablePynths(address account) external view returns (uint maxIssuable) {
return issuer().maxIssuablePynths(account);
}
function remainingIssuablePynths(address account)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
)
{
return issuer().remainingIssuablePynths(account);
}
function collateralisationRatio(address _issuer) external view returns (uint) {
return issuer().collateralisationRatio(_issuer);
}
function collateral(address account) external view returns (uint) {
return issuer().collateral(account);
}
function transferablePeriFinance(address account) external view returns (uint transferable) {
(transferable, ) = issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account));
}
function _canTransfer(address account, uint value) internal view returns (bool) {
require(!_isLocked(account, value), "PERI : Locked balance");
(uint initialDebtOwnership, ) = periFinanceState().issuanceData(account);
if (initialDebtOwnership > 0) {
(uint transferable, bool anyRateIsInvalid) =
issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account));
require(value <= transferable, "Cannot transfer staked or escrowed PERI");
require(!anyRateIsInvalid, "A pynth or PERI rate is invalid");
}
return true;
}
function setLock(
address account,
uint delay,
uint iterations,
uint totalLockAmount,
uint interval
) external onlyOwner {
uint _startTime = delay.add(block.timestamp);
uint _endTime = _startTime.add(iterations.mul(interval));
lockStates[account] = LockState(account, _startTime, iterations, totalLockAmount, interval, _endTime);
emit LockChanged(account, _startTime, iterations, totalLockAmount, interval, _endTime);
}
function resetLock(address account) external onlyOwner {
delete lockStates[account];
emit LockChanged(account, 0, 0, 0, 0, 0);
}
function getLock(address account)
public
view
returns (
address,
uint,
uint,
uint,
uint,
uint
)
{
return (
lockStates[account].account,
lockStates[account].startTime,
lockStates[account].iterations,
lockStates[account].totalAmount,
lockStates[account].unitTime,
lockStates[account].endTime
);
}
function getLockCalculation(address account) public view returns (uint, uint) {
LockState memory userLockInfo = lockStates[account];
// Releasing is not started yet, or user is not locked
if (userLockInfo.startTime > block.timestamp || userLockInfo.startTime == 0) {
return (userLockInfo.iterations, userLockInfo.totalAmount);
}
uint iterRemains = (userLockInfo.endTime.sub(block.timestamp)).div(userLockInfo.unitTime);
uint lockAmount = userLockInfo.totalAmount.mul(iterRemains).div(userLockInfo.iterations);
return (iterRemains, lockAmount);
}
function _isLocked(address account, uint amount) internal view returns (bool) {
LockState memory userLockInfo = lockStates[account];
// Account is not locked
if (userLockInfo.startTime == 0 || userLockInfo.endTime < block.timestamp) {
return false;
}
// Releasing is not started yet
if (userLockInfo.startTime > block.timestamp) {
return true;
}
(, uint lockAmount) = getLockCalculation(account);
uint accountBalance = tokenState.balanceOf(account);
// Account's remained balance may less than lock amount
if (accountBalance.sub(amount) < lockAmount) {
return true;
}
return false;
}
// ========== MUTATIVE FUNCTIONS ==========
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
_notImplemented();
return exchanger().exchange(messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender);
}
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
_notImplemented();
return
exchanger().exchangeOnBehalf(
exchangeForAddress,
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey
);
}
function settle(bytes32 currencyKey)
external
optionalProxy
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
_notImplemented();
return exchanger().settle(messageSender, currencyKey);
}
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
_notImplemented();
return
exchanger().exchangeWithTracking(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
messageSender,
originator,
trackingCode
);
}
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
_notImplemented();
return
exchanger().exchangeOnBehalfWithTracking(
exchangeForAddress,
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
originator,
trackingCode
);
}
function transfer(address to, uint value) external optionalProxy systemActive returns (bool) {
// Ensure they're not trying to exceed their locked amount -- only if they have debt.
_canTransfer(messageSender, value);
// Perform the transfer: if there is a problem an exception will be thrown in this call.
_transferByProxy(messageSender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint value
) external optionalProxy systemActive returns (bool) {
// Ensure they're not trying to exceed their locked amount -- only if they have debt.
_canTransfer(from, value);
// Perform the transfer: if there is a problem,
// an exception will be thrown in this call.
return _transferFromByProxy(messageSender, from, to, value);
}
function issuePynths(uint amount) external issuanceActive optionalProxy {
return issuer().issuePynths(messageSender, amount);
}
function issuePynthsOnBehalf(address issueForAddress, uint amount) external issuanceActive optionalProxy {
return issuer().issuePynthsOnBehalf(issueForAddress, messageSender, amount);
}
function issueMaxPynths() external issuanceActive optionalProxy {
return issuer().issueMaxPynths(messageSender);
}
function issueMaxPynthsOnBehalf(address issueForAddress) external issuanceActive optionalProxy {
return issuer().issueMaxPynthsOnBehalf(issueForAddress, messageSender);
}
function stakeUSDCAndIssuePynths(uint usdcStakeAmount, uint issueAmount) external issuanceActive optionalProxy {
return issuer().stakeUSDCAndIssuePynths(messageSender, usdcStakeAmount, issueAmount);
}
function stakeUSDCAndIssueMaxPynths(uint usdcStakeAmount) external issuanceActive optionalProxy {
return issuer().stakeUSDCAndIssueMaxPynths(messageSender, usdcStakeAmount);
}
function burnPynths(uint amount) external issuanceActive optionalProxy {
return issuer().burnPynths(messageSender, amount);
}
function burnPynthsOnBehalf(address burnForAddress, uint amount) external issuanceActive optionalProxy {
return issuer().burnPynthsOnBehalf(burnForAddress, messageSender, amount);
}
function burnPynthsToTarget() external issuanceActive optionalProxy {
return issuer().burnPynthsToTarget(messageSender);
}
function burnPynthsToTargetOnBehalf(address burnForAddress) external issuanceActive optionalProxy {
return issuer().burnPynthsToTargetOnBehalf(burnForAddress, messageSender);
}
function unstakeUSDCAndBurnPynths(uint usdcUnstakeAmount, uint burnAmount) external issuanceActive optionalProxy {
return issuer().unstakeUSDCAndBurnPynths(messageSender, usdcUnstakeAmount, burnAmount);
}
function unstakeUSDCToMaxAndBurnPynths(uint burnAmount) external issuanceActive optionalProxy {
return issuer().unstakeUSDCToMaxAndBurnPynths(messageSender, burnAmount);
}
function exchangeWithVirtual(
bytes32,
uint,
bytes32,
bytes32
) external returns (uint, IVirtualPynth) {
_notImplemented();
}
function mint() external returns (bool) {
_notImplemented();
}
function liquidateDelinquentAccount(address, uint) external returns (bool) {
_notImplemented();
}
function mintSecondary(address, uint) external {
_notImplemented();
}
function mintSecondaryRewards(uint) external {
_notImplemented();
}
function burnSecondary(address, uint) external {
_notImplemented();
}
function _notImplemented() internal pure {
revert("Cannot be run on this layer");
}
// ========== MODIFIERS ==========
modifier systemActive() {
_systemActive();
_;
}
function _systemActive() private {
systemStatus().requireSystemActive();
}
modifier issuanceActive() {
_issuanceActive();
_;
}
function _issuanceActive() private {
systemStatus().requireIssuanceActive();
}
modifier exchangeActive(bytes32 src, bytes32 dest) {
_exchangeActive(src, dest);
_;
}
function _exchangeActive(bytes32 src, bytes32 dest) private {
systemStatus().requireExchangeBetweenPynthsAllowed(src, dest);
}
modifier onlyExchanger() {
_onlyExchanger();
_;
}
function _onlyExchanger() private {
require(msg.sender == address(exchanger()), "Only Exchanger can invoke this");
}
// ========== EVENTS ==========
event PynthExchange(
address indexed account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
);
bytes32 internal constant PYNTHEXCHANGE_SIG =
keccak256("PynthExchange(address,bytes32,uint256,bytes32,uint256,address)");
function emitPynthExchange(
address account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
) external onlyExchanger {
proxy._emit(
abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress),
2,
PYNTHEXCHANGE_SIG,
addressToBytes32(account),
0,
0
);
}
event ExchangeTracking(bytes32 indexed trackingCode, bytes32 toCurrencyKey, uint256 toAmount);
bytes32 internal constant EXCHANGE_TRACKING_SIG = keccak256("ExchangeTracking(bytes32,bytes32,uint256)");
function emitExchangeTracking(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount
) external onlyExchanger {
proxy._emit(abi.encode(toCurrencyKey, toAmount), 2, EXCHANGE_TRACKING_SIG, trackingCode, 0, 0);
}
event ExchangeReclaim(address indexed account, bytes32 currencyKey, uint amount);
bytes32 internal constant EXCHANGERECLAIM_SIG = keccak256("ExchangeReclaim(address,bytes32,uint256)");
function emitExchangeReclaim(
address account,
bytes32 currencyKey,
uint256 amount
) external onlyExchanger {
proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGERECLAIM_SIG, addressToBytes32(account), 0, 0);
}
event ExchangeRebate(address indexed account, bytes32 currencyKey, uint amount);
bytes32 internal constant EXCHANGEREBATE_SIG = keccak256("ExchangeRebate(address,bytes32,uint256)");
function emitExchangeRebate(
address account,
bytes32 currencyKey,
uint256 amount
) external onlyExchanger {
proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGEREBATE_SIG, addressToBytes32(account), 0, 0);
}
}
// https://docs.peri.finance/contracts/source/interfaces/irewardescrow
interface IRewardEscrow {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingScheduleEntry(address account, uint index) external view returns (uint[2] memory);
function getNextVestingIndex(address account) external view returns (uint);
// Mutative functions
function appendVestingEntry(address account, uint quantity) external;
function vest() external;
}
pragma experimental ABIEncoderV2;
library VestingEntries {
struct VestingEntry {
uint64 endTime;
uint256 escrowAmount;
}
struct VestingEntryWithID {
uint64 endTime;
uint256 escrowAmount;
uint256 entryID;
}
}
interface IRewardEscrowV2 {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint);
function getVestingSchedules(
address account,
uint256 index,
uint256 pageSize
) external view returns (VestingEntries.VestingEntryWithID[] memory);
function getAccountVestingEntryIDs(
address account,
uint256 index,
uint256 pageSize
) external view returns (uint256[] memory);
function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint);
function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256);
// Mutative functions
function vest(uint256[] calldata entryIDs) external;
function createEscrowEntry(
address beneficiary,
uint256 deposit,
uint256 duration
) external;
function appendVestingEntry(
address account,
uint256 quantity,
uint256 duration
) external;
function migrateVestingSchedule(address _addressToMigrate) external;
function migrateAccountEscrowBalances(
address[] calldata accounts,
uint256[] calldata escrowBalances,
uint256[] calldata vestedBalances
) external;
// Account Merging
function startMergingWindow() external;
function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external;
function nominateAccountToMerge(address account) external;
function accountMergingIsOpen() external view returns (bool);
// L2 Migration
function importVestingEntries(
address account,
uint256 escrowedAmount,
VestingEntries.VestingEntry[] calldata vestingEntries
) external;
// Return amount of PERI transfered to PynthetixBridgeToOptimism deposit contract
function burnForMigration(address account, uint256[] calldata entryIDs)
external
returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries);
}
// https://docs.peri.finance/contracts/source/interfaces/isupplyschedule
interface ISupplySchedule {
// Views
function mintableSupply() external view returns (uint);
function isMintable() external view returns (bool);
function minterReward() external view returns (uint);
// Mutative functions
function recordMintEvent(uint supplyMinted) external returns (bool);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/periFinance
contract PeriFinance is BasePeriFinance {
// ========== ADDRESS RESOLVER CONFIGURATION ==========
bytes32 private constant CONTRACT_REWARD_ESCROW = "RewardEscrow";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_SUPPLYSCHEDULE = "SupplySchedule";
// ========== CONSTRUCTOR ==========
constructor(
address payable _proxy,
TokenState _tokenState,
address _owner,
uint _totalSupply,
address _resolver
) public BasePeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = BasePeriFinance.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](3);
newAddresses[0] = CONTRACT_REWARD_ESCROW;
newAddresses[1] = CONTRACT_REWARDESCROW_V2;
newAddresses[2] = CONTRACT_SUPPLYSCHEDULE;
return combineArrays(existingAddresses, newAddresses);
}
// ========== VIEWS ==========
function rewardEscrow() internal view returns (IRewardEscrow) {
return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARD_ESCROW));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function supplySchedule() internal view returns (ISupplySchedule) {
return ISupplySchedule(requireAndGetAddress(CONTRACT_SUPPLYSCHEDULE));
}
// ========== OVERRIDDEN FUNCTIONS ==========
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
)
external
exchangeActive(sourceCurrencyKey, destinationCurrencyKey)
optionalProxy
returns (uint amountReceived, IVirtualPynth vPynth)
{
_notImplemented();
return
exchanger().exchangeWithVirtual(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
messageSender,
trackingCode
);
}
function settle(bytes32 currencyKey)
external
optionalProxy
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
_notImplemented();
return exchanger().settle(messageSender, currencyKey);
}
function mint() external issuanceActive returns (bool) {
require(address(rewardsDistribution()) != address(0), "RewardsDistribution not set");
ISupplySchedule _supplySchedule = supplySchedule();
IRewardsDistribution _rewardsDistribution = rewardsDistribution();
uint supplyToMint = _supplySchedule.mintableSupply();
require(supplyToMint > 0, "No supply is mintable");
// record minting event before mutation to token supply
_supplySchedule.recordMintEvent(supplyToMint);
// Set minted PERI balance to RewardEscrow's balance
// Minus the minterReward and set balance of minter to add reward
uint minterReward = _supplySchedule.minterReward();
// Get the remainder
uint amountToDistribute = supplyToMint.sub(minterReward);
// Set the token balance to the RewardsDistribution contract
tokenState.setBalanceOf(
address(_rewardsDistribution),
tokenState.balanceOf(address(_rewardsDistribution)).add(amountToDistribute)
);
emitTransfer(address(this), address(_rewardsDistribution), amountToDistribute);
// Kick off the distribution of rewards
_rewardsDistribution.distributeRewards(amountToDistribute);
// Assign the minters reward.
tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));
emitTransfer(address(this), msg.sender, minterReward);
totalSupply = totalSupply.add(supplyToMint);
return true;
}
function liquidateDelinquentAccount(address account, uint pusdAmount)
external
systemActive
optionalProxy
returns (bool)
{
_notImplemented();
(uint totalRedeemed, uint amountLiquidated) =
issuer().liquidateDelinquentAccount(account, pusdAmount, messageSender);
emitAccountLiquidated(account, totalRedeemed, amountLiquidated, messageSender);
// Transfer PERI redeemed to messageSender
// Reverts if amount to redeem is more than balanceOf account, ie due to escrowed balance
return _transferByProxy(account, messageSender, totalRedeemed);
}
/* Once off function for SIP-60 to migrate PERI balances in the RewardEscrow contract
* To the new RewardEscrowV2 contract
*/
function migrateEscrowBalanceToRewardEscrowV2() external onlyOwner {
// Record balanceOf(RewardEscrow) contract
uint rewardEscrowBalance = tokenState.balanceOf(address(rewardEscrow()));
// transfer all of RewardEscrow's balance to RewardEscrowV2
// _internalTransfer emits the transfer event
_internalTransfer(address(rewardEscrow()), address(rewardEscrowV2()), rewardEscrowBalance);
}
// ========== EVENTS ==========
event AccountLiquidated(address indexed account, uint periRedeemed, uint amountLiquidated, address liquidator);
bytes32 internal constant ACCOUNTLIQUIDATED_SIG = keccak256("AccountLiquidated(address,uint256,uint256,address)");
function emitAccountLiquidated(
address account,
uint256 periRedeemed,
uint256 amountLiquidated,
address liquidator
) internal {
proxy._emit(
abi.encode(periRedeemed, amountLiquidated, liquidator),
2,
ACCOUNTLIQUIDATED_SIG,
addressToBytes32(account),
0,
0
);
}
} | ERROR: type should be string, got " https:docs.peri.finance/contracts/source/interfaces/iissuer Views Restricted: used internally to PeriFinance" | interface IIssuer {
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function canBurnPynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
function issuePynths(address from, uint amount) external;
function issuePynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxPynths(address from) external;
function issueMaxPynthsOnBehalf(address issueFor, address from) external;
function stakeUSDCAndIssuePynths(
address from,
uint usdcStakeAmount,
uint issueAmount
) external;
function stakeUSDCAndIssueMaxPynths(address from, uint usdcStakeAmount) external;
function burnPynths(address from, uint amount) external;
function burnPynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnPynthsToTarget(address from) external;
function burnPynthsToTargetOnBehalf(address burnForAddress, address from) external;
function unstakeUSDCAndBurnPynths(
address from,
uint usdcUnstakeAmount,
uint burnAmount
) external;
function unstakeUSDCToMaxAndBurnPynths(address from, uint burnAmount) external;
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
| 1,197,823 | [
1,
4528,
30,
8532,
18,
457,
77,
18,
926,
1359,
19,
16351,
87,
19,
3168,
19,
15898,
19,
77,
17567,
31117,
29814,
30,
1399,
12963,
358,
5722,
77,
6187,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
16667,
288,
203,
565,
445,
1281,
52,
878,
451,
1162,
3194,
45,
4727,
2520,
1941,
1435,
3903,
1476,
1135,
261,
6430,
1281,
4727,
1941,
1769,
203,
203,
565,
445,
2319,
7623,
2396,
1435,
3903,
1476,
1135,
261,
3890,
1578,
8526,
3778,
1769,
203,
203,
565,
445,
2319,
52,
878,
451,
1380,
1435,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
2319,
52,
878,
451,
87,
12,
11890,
770,
13,
3903,
1476,
1135,
261,
2579,
878,
451,
1769,
203,
203,
565,
445,
848,
38,
321,
52,
878,
451,
87,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
4508,
2045,
287,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
4508,
2045,
287,
10742,
8541,
12,
2867,
9715,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
4508,
2045,
287,
10742,
8541,
1876,
2961,
20836,
1941,
12,
2867,
389,
17567,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
4422,
4197,
16,
1426,
1281,
4727,
2520,
1941,
1769,
203,
203,
565,
445,
18202,
88,
13937,
951,
12,
2867,
9715,
16,
1731,
1578,
5462,
653,
13,
3903,
1476,
1135,
261,
11890,
18202,
88,
13937,
1769,
203,
203,
565,
445,
3385,
89,
1359,
8541,
1435,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
1142,
12956,
1133,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
943,
7568,
89,
429,
52,
878,
451,
87,
12,
2867,
9715,
13,
3903,
1476,
1135,
261,
2
] |
pragma solidity 0.5.11;
pragma experimental ABIEncoderV2;
import "../../framework/PlasmaFramework.sol";
import "../../framework/Protocol.sol";
import "../../utils/Merkle.sol";
import "../../utils/PosLib.sol";
import "../../transactions/GenericTransaction.sol";
/**
* @notice Library to check finalization for MoreVP protocol
* @dev This library assumes that the tx is of the GenericTransaction format
*/
library MoreVpFinalization {
using PosLib for PosLib.Position;
/**
* @notice Checks whether a transaction is "standard finalized".
* For MoreVP, it means the transaction should be included in a plasma block.
*/
function isStandardFinalized(
PlasmaFramework framework,
bytes memory txBytes,
PosLib.Position memory txPos,
bytes memory inclusionProof
)
internal
view
returns (bool)
{
require(txPos.outputIndex == 0, "Invalid transaction position");
GenericTransaction.Transaction memory genericTx = GenericTransaction.decode(txBytes);
uint8 protocol = framework.protocols(genericTx.txType);
require(protocol == Protocol.MORE_VP(), "MoreVpFinalization: not a MoreVP protocol tx");
(bytes32 root,) = framework.blocks(txPos.blockNum);
require(root != bytes32(""), "Failed to get the root hash of the block num");
return Merkle.checkMembership(
txBytes, txPos.txIndex, root, inclusionProof
);
}
/**
* @notice Checks whether a transaction is "protocol finalized"
* For MoreVP, since it allows in-flight tx, so only checks for the existence of the transaction
*/
function isProtocolFinalized(
PlasmaFramework framework,
bytes memory txBytes
)
internal
view
returns (bool)
{
if (txBytes.length == 0) {
return false;
}
GenericTransaction.Transaction memory genericTx = GenericTransaction.decode(txBytes);
uint8 protocol = framework.protocols(genericTx.txType);
require(protocol == Protocol.MORE_VP(), "MoreVpFinalization: not a MoreVP protocol tx");
return true;
}
}
| * @notice Checks whether a transaction is "protocol finalized" For MoreVP, since it allows in-flight tx, so only checks for the existence of the transaction/ | function isProtocolFinalized(
PlasmaFramework framework,
bytes memory txBytes
)
internal
view
returns (bool)
{
if (txBytes.length == 0) {
return false;
}
GenericTransaction.Transaction memory genericTx = GenericTransaction.decode(txBytes);
uint8 protocol = framework.protocols(genericTx.txType);
require(protocol == Protocol.MORE_VP(), "MoreVpFinalization: not a MoreVP protocol tx");
return true;
}
| 1,830,076 | [
1,
4081,
2856,
279,
2492,
353,
315,
8373,
727,
1235,
6,
540,
2457,
16053,
26152,
16,
3241,
518,
5360,
316,
17,
19131,
2229,
16,
1427,
1338,
4271,
364,
326,
15782,
434,
326,
2492,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
5752,
7951,
1235,
12,
203,
3639,
3008,
345,
2540,
13701,
8257,
16,
203,
3639,
1731,
3778,
2229,
2160,
203,
565,
262,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
309,
261,
978,
2160,
18,
2469,
422,
374,
13,
288,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
203,
3639,
7928,
3342,
18,
3342,
3778,
5210,
4188,
273,
7928,
3342,
18,
3922,
12,
978,
2160,
1769,
203,
3639,
2254,
28,
1771,
273,
8257,
18,
31018,
12,
13540,
4188,
18,
978,
559,
1769,
203,
3639,
2583,
12,
8373,
422,
4547,
18,
31078,
67,
26152,
9334,
315,
7417,
58,
84,
7951,
1588,
30,
486,
279,
16053,
26152,
1771,
2229,
8863,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-05-06
*/
pragma solidity 0.5.10;
// ----------------------------------------------------------------------------
// WUMI token contract (2021)
//
// Symbol : WUMI
// Name : WUMI
// Total supply : 1.175.000 (burnable)
// Decimals : 18
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); }
function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; }
function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); }
function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; }
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view 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 function to receive approval and execute function in one call
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint tokens, address token, bytes memory data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address transferOwner) public onlyOwner {
require(transferOwner != newOwner);
newOwner = transferOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// WUMI ERC20 Token
// ----------------------------------------------------------------------------
contract WUMI is ERC20Interface, Owned {
using SafeMath for uint;
bool public running = true;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Contract init. Set symbol, name, decimals and initial fixed supply
// ------------------------------------------------------------------------
constructor() public {
symbol = "WUMI";
name = "WUMI";
decimals = 18;
_totalSupply = 1175000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Start-stop contract functions:
// transfer, approve, transferFrom, approveAndCall
// ------------------------------------------------------------------------
modifier isRunning {
require(running);
_;
}
function startStop () public onlyOwner returns (bool success) {
if (running) { running = false; } else { running = true; }
return true;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public isRunning returns (bool success) {
require(tokens <= balances[msg.sender]);
require(to != address(0));
_transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Internal transfer function
// ------------------------------------------------------------------------
function _transfer(address from, address to, uint256 tokens) internal {
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Increase the amount of tokens that an owner allowed to a spender.
// ------------------------------------------------------------------------
function increaseAllowance(address spender, uint addedTokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, allowed[msg.sender][spender].add(addedTokens));
return true;
}
// ------------------------------------------------------------------------
// Decrease the amount of tokens that an owner allowed to a spender.
// ------------------------------------------------------------------------
function decreaseAllowance(address spender, uint subtractedTokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, allowed[msg.sender][spender].sub(subtractedTokens));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public isRunning returns (bool success) {
_approve(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Approve an address to spend another addresses' tokens.
// ------------------------------------------------------------------------
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0));
require(spender != address(0));
allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public isRunning returns (bool success) {
require(to != address(0));
_approve(from, msg.sender, allowed[from][msg.sender].sub(tokens));
_transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Tokens burn
// ------------------------------------------------------------------------
function burnTokens(uint tokens) public returns (bool success) {
require(tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
_totalSupply = _totalSupply.sub(tokens);
emit Transfer(msg.sender, address(0), tokens);
return true;
}
// ------------------------------------------------------------------------
// Tokens multisend from owner only by owner
// ------------------------------------------------------------------------
function multisend(address[] memory to, uint[] memory values) public onlyOwner returns (uint) {
require(to.length == values.length);
require(to.length < 100);
uint sum;
for (uint j; j < values.length; j++) {
sum += values[j];
}
balances[owner] = balances[owner].sub(sum);
for (uint i; i < to.length; i++) {
balances[to[i]] = balances[to[i]].add(values[i]);
emit Transfer(owner, to[i], values[i]);
}
return(to.length);
}
} | ------------------------------------------------------------------------ Decrease the amount of tokens that an owner allowed to a spender. ------------------------------------------------------------------------ | function decreaseAllowance(address spender, uint subtractedTokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, allowed[msg.sender][spender].sub(subtractedTokens));
return true;
}
| 10,786,943 | [
1,
29461,
31073,
448,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
10418,
329,
5157,
13,
1071,
19858,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
389,
12908,
537,
12,
3576,
18,
15330,
16,
17571,
264,
16,
2935,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
8009,
1717,
12,
1717,
1575,
329,
5157,
10019,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x425821CF3B6Ac284cC432c660cAccD27C5ebBE57/sources/browser/IBXRE.sol | Check to see if address is added to the whiteList | function isWhiteListed(address a) private view returns (bool) {
if (whiteList[a] == 1) {
return true;
}
else return false;
}
| 14,170,122 | [
1,
1564,
358,
2621,
309,
1758,
353,
3096,
358,
326,
27859,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
13407,
682,
329,
12,
2867,
279,
13,
3238,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
14739,
682,
63,
69,
65,
422,
404,
13,
288,
203,
5411,
327,
638,
31,
203,
3639,
289,
7010,
3639,
469,
327,
629,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42161/0x78f5B56cc94719111010b3d99B52ADEFE0b8E8c8/sources/GMS/GMSstaking.sol | WETH tokens created per block. | uint256 public WETHPerSecond;
| 16,307,982 | [
1,
59,
1584,
44,
2430,
2522,
1534,
1203,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
678,
1584,
44,
2173,
8211,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xa33C3162BD3AE64e81DbC88765B6f719C90c5B28/sources/contracts/ZuttoMamo.sol | * @dev Hook that is called after a set of serially-ordered token IDs have been transferred. This includes minting. And also called after one token has been burned. If the transferred token ID is in sleep mode, the current time is set./ | function _afterTokenTransfers(address _from, address _to, uint256 _tokenId, uint256 _quantity) internal override {
if (tokenLocation[_tokenId] == DataType.TokenLocation.Operator) {
if (zuttoMamoStage.getTimeGrowingUpToHighSchooler() <= block.timestamp) {
zuttoMamoStage.setHighSchoolerLock(_tokenId);
}
tokenLocation[_tokenId] = DataType.TokenLocation.Other;
}
super._afterTokenTransfers(_from, _to, _tokenId, _quantity);
}
| 16,430,346 | [
1,
5394,
716,
353,
2566,
1839,
279,
444,
434,
703,
6261,
17,
9885,
1147,
7115,
1240,
2118,
906,
4193,
18,
1220,
6104,
312,
474,
310,
18,
7835,
2546,
2566,
1839,
1245,
1147,
711,
2118,
18305,
329,
18,
971,
326,
906,
4193,
1147,
1599,
353,
316,
5329,
1965,
16,
326,
783,
813,
353,
444,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
389,
5205,
1345,
1429,
18881,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
16172,
13,
2713,
3849,
288,
203,
202,
202,
430,
261,
2316,
2735,
63,
67,
2316,
548,
65,
422,
14828,
18,
1345,
2735,
18,
5592,
13,
288,
203,
1082,
202,
430,
261,
94,
322,
869,
49,
301,
83,
8755,
18,
588,
950,
30948,
310,
1211,
774,
8573,
55,
343,
1371,
264,
1435,
1648,
1203,
18,
5508,
13,
288,
203,
9506,
202,
94,
322,
869,
49,
301,
83,
8755,
18,
542,
8573,
55,
343,
1371,
264,
2531,
24899,
2316,
548,
1769,
203,
1082,
202,
97,
203,
1082,
202,
2316,
2735,
63,
67,
2316,
548,
65,
273,
14828,
18,
1345,
2735,
18,
8290,
31,
203,
202,
202,
97,
203,
202,
202,
9565,
6315,
5205,
1345,
1429,
18881,
24899,
2080,
16,
389,
869,
16,
389,
2316,
548,
16,
389,
16172,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0x68602205724124714992817612b9d93E8d39Bdc6/sources/PhilippePhix.sol | Total supply counter. | function totalSupply () public view returns (uint256) {
return _supply.current();
}
| 3,811,548 | [
1,
5269,
14467,
3895,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
1832,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
2859,
1283,
18,
2972,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xD02A7208809821bC465BfBA4865D544cC48a93E8/sources/contracts/NFTStandard.sol | * @notice Return client ids mapped to given token ids @dev Throws if any of given token ids is not minted. @param _tokenIds Token ids to query client ids. @return clientIds The array of client ids/ | function clientIdBatch(uint256[] calldata _tokenIds)
external
view
virtual
returns (uint256[] memory)
{
uint256[] memory clientIds = new uint256[](_tokenIds.length);
uint256 id;
uint256 clid;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
id = _tokenIds[i];
clid = tokenIdClientId[id];
require(
_exists(id),
string(abi.encodePacked("NS8, ", id.toString()))
);
require(
clid != 0,
string(abi.encodePacked("NS9, ", id.toString()))
);
clientIds[i] = clid;
}
return clientIds;
}
| 3,037,575 | [
1,
990,
1004,
3258,
5525,
358,
864,
1147,
3258,
225,
22435,
309,
1281,
434,
864,
1147,
3258,
353,
486,
312,
474,
329,
18,
225,
389,
2316,
2673,
3155,
3258,
358,
843,
1004,
3258,
18,
327,
1004,
2673,
1021,
526,
434,
1004,
3258,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11493,
4497,
12,
11890,
5034,
8526,
745,
892,
389,
2316,
2673,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
1135,
261,
11890,
5034,
8526,
3778,
13,
203,
565,
288,
203,
3639,
2254,
5034,
8526,
3778,
1004,
2673,
273,
394,
2254,
5034,
8526,
24899,
2316,
2673,
18,
2469,
1769,
203,
3639,
2254,
5034,
612,
31,
203,
3639,
2254,
5034,
927,
350,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
2316,
2673,
18,
2469,
31,
965,
77,
13,
288,
203,
5411,
612,
273,
389,
2316,
2673,
63,
77,
15533,
203,
5411,
927,
350,
273,
1147,
548,
23526,
63,
350,
15533,
203,
5411,
2583,
12,
203,
7734,
389,
1808,
12,
350,
3631,
203,
7734,
533,
12,
21457,
18,
3015,
4420,
329,
2932,
3156,
28,
16,
3104,
612,
18,
10492,
1435,
3719,
203,
5411,
11272,
203,
5411,
2583,
12,
203,
7734,
927,
350,
480,
374,
16,
203,
7734,
533,
12,
21457,
18,
3015,
4420,
329,
2932,
3156,
29,
16,
3104,
612,
18,
10492,
1435,
3719,
203,
5411,
11272,
203,
5411,
1004,
2673,
63,
77,
65,
273,
927,
350,
31,
203,
3639,
289,
203,
3639,
327,
1004,
2673,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/Math.sol';
import './interfaces/IOracle.sol';
import './interfaces/IBoardroom.sol';
import './interfaces/IBasisAsset.sol';
import './interfaces/ISimpleERCFund.sol';
import './interfaces/ITreasury.sol';
import './interfaces/IRewardPool.sol';
import './lib/FixedPoint.sol';
import './utils/Epoch.sol';
import './lib/Safe112.sol';
import './lib/AdminRole.sol';
import './utils/ContractGuard.sol';
/**
* @title GoCash Cash Treasury合约
* 实现功能:
* 1.通过预言机获取GOC价格,根据GOC价格不同,用GOC购买GOB,或赎回GOB获得GOC
* 2.根据GOC价格不同,增发GOC,并把新增发的GOC分配给fund treasury shareBoardroom
* 注解:TimBear 20210107
* @notice Monetary policy logic to adjust supplies of basis cash assets
* @author Summer Smith & Rick Sanchez
*/
contract Treasury is ContractGuard, Epoch {
using FixedPoint for *;
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using Safe112 for uint112;
/* ========== STATE VARIABLES ========== */
// ========== FLAGS 标记
/// @notice 已迁移
bool public migrated = false;
/// @notice 已初始化
bool public initialized = false;
// ========== CORE 核心
/// @notice 开发者基金
address public fund;
/// @notice GoCash Cash地址
address public cash;
/// @notice GoCash Bond地址
address public bond;
/// @notice GoCash Token地址
address public share;
/// @notice share质押董事会合约地址
address public shareBoardroom;
/// @notice lp质押董事会合约地址
address public lpBoardroom;
/// @notice bond奖励池地址
address public bondRewardPool;
/// @notice 预言机地址
address public oracle;
// ========== PARAMS 参数
/// @notice cash基准价格
uint256 public cashPriceOne;
/// @notice oracle基准价格
uint256 public oraclePriceOne;
/// @notice 价格天花板
uint256 public cashPriceCeiling;
/// @notice cash价格下限
uint256 public cashPriceFloor;
/// @notice cash价格bond奖励
uint256 public cashPriceBondReward;
/// @notice bond基准价格 1
uint256 public bondPrice;
/// @notice 最低bond价格 0.5
uint256 public minBondPrice;
/// @notice bondPriceDelta 0.02
uint256 public bondPriceDelta;
/// @dev 累计铸币税
uint256 private accumulatedSeigniorage = 0;
/// @notice 开发者基金分配比例 2%
uint256 public fundAllocationRate = 2; // %
/// @dev 累计债务
uint256 private accumulatedDebt = 0;
/// @notice 最大通胀率
uint256 public maxInflationRate = 10;
/// @notice 债务增加比率
uint256 public debtAddRate = 2;
/// @notice 最大债务比率
uint256 public maxDebtRate = 20;
// ========== MIGRATE
/// @dev 旧国库合约地址
address public legacyTreasury;
/* ========== CONSTRUCTOR ========== */
/**
* @dev 构造函数
* @param _cash GoCash Cash地址
* @param _bond GoCash Bond地址
* @param _share GoCash Token地址
* @param _oracle Bond预言机地址
* @param _shareBoardroom share质押董事会合约地址
* @param _lpBoardroom lp质押董事会合约地址
* @param _bondRewardPool bond奖励池地址
* @param _fund 开发者基金
* @param _startTime 开始时间
*/
constructor(
address _cash,
address _bond,
address _share,
address _oracle,
address _shareBoardroom,
address _lpBoardroom,
address _bondRewardPool,
address _fund,
uint256 _startTime
) public Epoch(12 hours, _startTime, 0) {
cash = _cash;
bond = _bond;
share = _share;
oracle = _oracle;
shareBoardroom = _shareBoardroom;
lpBoardroom = _lpBoardroom;
bondRewardPool = _bondRewardPool;
fund = _fund;
// Cash基准价格为1
cashPriceOne = 10**18;
// oracle基准价格,防止有些token精度不是18
oraclePriceOne = 10**18;
// cash价格天花板为1.02 102 * 10**18 / 10**2 = 1.05
cashPriceCeiling = uint256(102).mul(cashPriceOne).div(10**2);
// band亏损下限 1000 * 10**18
// bondDepletionFloor = uint256(1000).mul(cashPriceOne);
// cash价格下限 98 * 10**18 / 10**2 = 0.98
cashPriceFloor = uint256(98).mul(cashPriceOne).div(10**2);
// cash价格bond奖励 95 * 10**18 / 10**2 = 0.98
cashPriceBondReward = uint256(95).mul(cashPriceOne).div(10**2);
// bond基准价格
bondPrice = 10**18;
// 最低bond基准价格 0.5
minBondPrice = 5 * 10**17;
// bond基准价Delta 0.02
bondPriceDelta = 2 * 10**16;
}
/* =================== Modifier =================== */
/// @notice 修饰符:需要完成Migration,即完成更换Admin为本合约
modifier checkMigration {
require(!migrated, 'Treasury: migrated');
_;
}
/// @notice 修饰符:合约cash bond share boardroom的Admin必须为本合约
modifier checkAdmin {
require(
AdminRole(cash).isAdmin(address(this)) &&
AdminRole(bond).isAdmin(address(this)) &&
AdminRole(share).isAdmin(address(this)) &&
AdminRole(bondRewardPool).isAdmin(address(this)) &&
AdminRole(lpBoardroom).isAdmin(address(this)) &&
AdminRole(shareBoardroom).isAdmin(address(this)),
'Treasury: need more permission'
);
_;
}
/* ========== VIEW FUNCTIONS ========== */
//一些只读方法
/**
* @dev 返回累计铸币税,预算?
* @return 预算
*/
function getReserve() public view returns (uint256) {
return accumulatedSeigniorage;
}
// debt
/**
* @dev 返回债务
* @return 累计债务
*/
function getDebt() public view returns (uint256) {
return accumulatedDebt;
}
// oracle
/**
* @dev 返回预言机中Cash价格
* @return 价格
*/
function getOraclePrice() public view returns (uint256) {
// 通过预言机取Cash价格
return _getCashPrice(oracle);
}
/**
* @dev 根据不同的场景选择不同的预言机进行喂价
* @param _oracle 预言机地址
* @return 价格
*/
function _getCashPrice(address _oracle) internal view returns (uint256) {
try IOracle(_oracle).consult(cash, 1e18) returns (uint256 price) {
// 返回价格 * 1e18 / 1e18 防止有些token精度不是18
return price.mul(cashPriceOne).div(oraclePriceOne);
} catch {
revert('Treasury: failed to consult cash price from the oracle');
}
}
/* ========== GOVERNANCE ========== */
/**
* @dev 设置旧国库合约地址
*/
function setLegacyTreasury(address _legacyTreasury) public onlyAdmin {
legacyTreasury = _legacyTreasury;
}
/**
* @dev 合约初始化
* @param _accumulatedSeigniorage 累计铸币税
* @param _accumulatedDebt 累计债务
* @param _bondPrice bond基准价格
* @param _oraclePriceOne 预言机基准价格
*/
function initialize(
uint256 _accumulatedSeigniorage,
uint256 _accumulatedDebt,
uint256 _bondPrice,
uint256 _oraclePriceOne
) public {
// 确认合约未经初始化
require(!initialized, 'Treasury: initialized');
// 确认必须由旧国库合约调用
require(msg.sender == legacyTreasury, 'Treasury: on legacy treasury');
// 变量赋值
accumulatedSeigniorage = _accumulatedSeigniorage;
accumulatedDebt = _accumulatedDebt;
bondPrice = _bondPrice;
oraclePriceOne = _oraclePriceOne;
initialized = true;
//触发合约初始化事件
emit Initialized(msg.sender, block.number);
}
/**
* @dev 迁移国库合约到新合约
* @param target 目标地址
*/
function migrate(address target) public onlyAdmin checkAdmin {
require(!migrated, 'Treasury: migrated');
// cash
//更换GOC合约的Admin,Owner为target,并把原合约的GOC发送至target
AdminRole(cash).addAdmin(target);
AdminRole(cash).renounceAdmin();
IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this)));
// bond
//更换GOB合约的Admin,Owner为target,并把原合约的GOB发送至target
AdminRole(bond).addAdmin(target);
AdminRole(bond).renounceAdmin();
IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
// share
//更换GOT合约的Admin,Owner为target,并把原合约的GOT发送至target
AdminRole(share).addAdmin(target);
AdminRole(share).renounceAdmin();
IERC20(share).transfer(target, IERC20(share).balanceOf(address(this)));
// Boardroom
//更换boardroom合约的Admin
AdminRole(bondRewardPool).addAdmin(target);
AdminRole(bondRewardPool).renounceAdmin();
AdminRole(shareBoardroom).addAdmin(target);
AdminRole(shareBoardroom).renounceAdmin();
AdminRole(lpBoardroom).addAdmin(target);
AdminRole(lpBoardroom).renounceAdmin();
// params
ITreasury(target).initialize(
accumulatedSeigniorage,
accumulatedDebt,
bondPrice,
oraclePriceOne
);
migrated = true;
//触发所有权转移事件
emit Migration(target);
}
/**
* @dev 设置开发者基金地址
* @param newFund 新开发者基金地址
*/
function setFund(address newFund) public onlyAdmin {
//设置开发贡献者奖金池
fund = newFund;
//触发更换开发贡献者奖金池事件
emit ContributionPoolChanged(msg.sender, newFund);
}
/**
* @dev 设置开发者奖励比例
* @param rate 新比例
*/
function setFundAllocationRate(uint256 rate) public onlyAdmin {
//设置开发贡献者奖金比例
fundAllocationRate = rate;
//触发更换开发贡献者奖金比例事件
emit ContributionPoolRateChanged(msg.sender, rate);
}
/**
* @dev 设置预言机基准价格1
* @param _oraclePriceOne 新基准价格1
*/
function setOraclePriceOne(uint256 _oraclePriceOne) public onlyAdmin {
oraclePriceOne = _oraclePriceOne;
//触发事件
emit SetOraclePriceOne(oraclePriceOne);
}
/**
* @dev 设置最大通胀比例
* @param rate 最大通胀比例
*/
function setMaxInflationRate(uint256 rate) public onlyAdmin {
maxInflationRate = rate;
emit MaxInflationRateChanged(msg.sender, rate);
}
/**
* @dev 设置债务增加比率
* @param rate 债务增加比率
*/
function setDebtAddRate(uint256 rate) public onlyAdmin {
debtAddRate = rate;
emit DebtAddRateChanged(msg.sender, rate);
}
/**
* @dev 设置最大债务比例
* @param rate 最大债务比例
*/
function setMaxDebtRate(uint256 rate) public onlyAdmin {
maxDebtRate = rate;
emit MaxDebtRateChanged(msg.sender, rate);
}
/* ========== MUTABLE FUNCTIONS ========== */
/**
* @dev 预言机更新GOC价格
*/
function _updateCashPrice() internal {
try IOracle(oracle).update() {} catch {}
}
/**
* @dev 当GOC价格低于1时,使用GOC购买GOB
* @param amount 购买数额
*/
function buyBonds(uint256 amount)
external
onlyOneBlock // 同一区块只能调用一次合约
checkMigration // 检查是否迁移
checkStartTime // 检查开始时间
checkAdmin // 检查铸币权限
{
//通过预言机获取GOC价格
uint256 cashPrice = _getCashPrice(oracle);
//需要GOC价格小于1
require(
cashPrice < cashPriceOne, // price < $1
'Treasury: cashPrice not eligible for bond purchase'
);
// 销毁数量 = 最小值(购买数量,累计债务 * bond基准价 / 1e18)
uint256 burnAmount = Math.min(
amount,
accumulatedDebt.mul(bondPrice).div(1e18)
);
// 确认销毁数量 > 0
require(
burnAmount > 0,
'Treasury: cannot purchase bonds with zero amount'
);
// 铸造bond数量 = 销毁数量 * 1e18 / bond基准价
uint256 mintBondAmount = burnAmount.mul(1e18).div(bondPrice);
//销毁用户持有的amount数量的GOC
IBasisAsset(cash).burnFrom(msg.sender, burnAmount);
//铸造GOB: 铸造bond数量
IBasisAsset(bond).mint(msg.sender, mintBondAmount);
// 累计债务 = 累计债务 - 铸造bond数量
accumulatedDebt = accumulatedDebt.sub(mintBondAmount);
//更新GOC价格
_updateCashPrice();
//触发购买GOB事件
emit BoughtBonds(msg.sender, amount);
}
/**
* @dev 当GOC价格大于1.05时,使用GOB换回GOC
* @param amount 赎回数额
*/
function redeemBonds(uint256 amount)
external
onlyOneBlock // 同一区块只能调用一次合约
checkMigration // 检查是否迁移
checkStartTime // 检查开始时间
checkAdmin // 检查铸币权限
{
//通过预言机获取GOC价格
uint256 cashPrice = _getCashPrice(oracle);
// 确认GOC价格大于cashPriceCeiling,即1.02
require(
cashPrice > cashPriceCeiling, // price > $1.02
'Treasury: cashPrice not eligible for bond purchase'
);
// 赎回数量 = 最小值(GOC的累计储备量,赎回数额)
uint256 redeemAmount = Math.min(accumulatedSeigniorage, amount);
// 确认赎回数量>0
require(
redeemAmount > 0,
'Treasury: cannot redeem bonds with zero amount'
);
// 确认当前合约的GOC数量大于要赎回的GOB数量
require(
IERC20(cash).balanceOf(address(this)) >= redeemAmount,
'Treasury: treasury has no more budget'
);
// GOC的累计储备量 = 累计储备量 - 赎回数量,即1GOB换取1GOC
accumulatedSeigniorage = accumulatedSeigniorage.sub(redeemAmount);
// 销毁用户持有的GOB
IBasisAsset(bond).burnFrom(msg.sender, redeemAmount);
// 将当前合约的GOC发送给用户
IERC20(cash).safeTransfer(msg.sender, redeemAmount);
// 更新GOC价格
_updateCashPrice();
// 触发赎回GOB事件
emit RedeemedBonds(msg.sender, amount);
}
/**
* @dev 增发GOC,并分配GOC
*/
function allocateSeigniorage()
external
onlyOneBlock
checkMigration
checkStartTime
checkEpoch
checkAdmin
{
//更新GOC价格
_updateCashPrice();
//通过预言机获取GOC价格
uint256 cashPrice = _getCashPrice(oracle);
// circulating supply
// 流通的GOC数量 = GOC总供应量 - GOC累计储备量
uint256 cashSupply = IERC20(cash).totalSupply().sub(
accumulatedSeigniorage
);
//判断当GOC价格小于等于cashPriceBondReward即小于0.95
if (cashPrice <= cashPriceBondReward) {
// 奖励数量 = bond的1%
uint256 rewardAmount = IERC20(bond).totalSupply().div(100);
// bond铸造奖励,发给bond奖励池
IBasisAsset(bond).mint(bondRewardPool, rewardAmount);
// bond奖励池通知奖励数量
IRewardPool(bondRewardPool).notifyRewardAmount(rewardAmount);
// 触发奖励事件
emit BondReward(block.timestamp, rewardAmount);
}
// add debt
//判断当GOC价格小于等于0.98(cash价格下限)
if (cashPrice <= cashPriceFloor) {
// 增加债务 = 流通的GOC数量 * 2%(债务增加比率)
uint256 addDebt = cashSupply.mul(debtAddRate).div(100);
// 最大债务 = 流通的GOC数量 * 20%(最大债务比率)
uint256 maxDebt = cashSupply.mul(maxDebtRate).div(100);
// 累计债务 = 累计债务 + 增加的债务
accumulatedDebt = accumulatedDebt.add(addDebt);
// 如果累计债务 > 最大债务
if (accumulatedDebt > maxDebt) {
// 累计债务 = 最大债务 20%
accumulatedDebt = maxDebt;
}
// bond基准价 = bond基准价 - 0.02(bond基准价Delta)
bondPrice = bondPrice.sub(bondPriceDelta);
// 如果 bond基准价 <= 0.5(最低bond基准价格)
if (bondPrice <= minBondPrice) {
// bond基准价 = 0.5(最低bond基准价格)
bondPrice = minBondPrice;
}
}
// clear the debt
// 如果GOC价格>0.98(cash价格下限)
if (cashPrice > cashPriceFloor) {
// 累计债务清零
accumulatedDebt = 0;
// bond价格=1
bondPrice = 10**18;
}
//判断当GOC价格小于等于cashPriceCeiling即小于1.05则返回,不增发GOC
if (cashPrice <= cashPriceCeiling) {
return; // just advance epoch instead revert
}
//增发比例 = GOC价格 - 1 例:0.8
uint256 percentage = cashPrice.sub(cashPriceOne);
//新铸造的GOC数量 = 流通的GOC数量 * 增发比例
uint256 seigniorage = cashSupply.mul(percentage).div(1e18);
// 最大铸造的GOC数量 = 流通的GOC数量 * 10%(最大通胀比例)
uint256 maxSeigniorage = cashSupply.mul(maxInflationRate).div(100);
// 如果新铸造的GOC数量 > 最大铸造的GOC数量
if (seigniorage > maxSeigniorage) {
// 新铸造的GOC数量 = 最大铸造的GOC数量
seigniorage = maxSeigniorage;
}
//新铸造GOC,并发送至本合约
IBasisAsset(cash).mint(address(this), seigniorage);
// ======================== BIP-3
// 开发者基金储备 = 新铸造的GOC数量 * fundAllocationRate / 100 = 新铸造的GOC数量 * 2%
uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100);
if (fundReserve > 0) {
// 当前合约批准fund地址,开发者准备金数额
IERC20(cash).safeApprove(fund, fundReserve);
// 调用fund合约的存款方法存入开发者准备金
ISimpleERCFund(fund).deposit(
cash,
fundReserve,
'Treasury: Seigniorage Allocation'
);
//触发GOC已发放至开发贡献池事件
emit ContributionPoolFunded(now, fundReserve);
}
//新铸造的GOC数量 = 新铸造的GOC数量 - 开发者基金储备
seigniorage = seigniorage.sub(fundReserve);
// ======================== BIP-4
//新增国库储备 = min(新铸造的GOC数量 / 2, GOB总供应量-累计GOC储备量)
//即新铸造的GOC要先预留给GOB,剩下的才能分配给Boardroom
uint256 treasuryReserve = Math.min(
seigniorage.div(2), // 只有50%的通胀
IERC20(bond).totalSupply().sub(accumulatedSeigniorage)
);
// 如果 新增国库储备 > 0
if (treasuryReserve > 0) {
//累计GOC储备量 = 累计GOC储备量 + 新增国库储备量
accumulatedSeigniorage = accumulatedSeigniorage.add(
treasuryReserve
);
//触发已发放国库储备事件
emit TreasuryFunded(now, treasuryReserve);
}
// shareBoardroom
//董事会GOC新增储备量 = 新铸造的GOC - 新增国库储备量
uint256 boardroomReserve = seigniorage.sub(treasuryReserve);
if (boardroomReserve > 0) {
// share董事会分到60%
uint256 shareBoardroomReserve = boardroomReserve.mul(6).div(10);
// lp董事会分到40%
uint256 lpBoardroomReserve = boardroomReserve.sub(shareBoardroomReserve);
// 批准国库合约储备量数额
IERC20(cash).safeApprove(shareBoardroom, shareBoardroomReserve);
//调用Boardroom合约的allocateSeigniorage方法,将GOC存入董事会
IBoardroom(shareBoardroom).allocateSeigniorage(shareBoardroomReserve);
// 批准国库合约储备量数额
IERC20(cash).safeApprove(lpBoardroom, lpBoardroomReserve);
//调用Boardroom合约的allocateSeigniorage方法,将GOC存入董事会
IBoardroom(lpBoardroom).allocateSeigniorage(lpBoardroomReserve);
//触发已发放资金至董事会事件
emit BoardroomFunded(now, boardroomReserve);
}
}
// GOV
event Initialized(address indexed executor, uint256 at);
event Migration(address indexed target);
event ContributionPoolChanged(address indexed operator, address newFund);
event ContributionPoolRateChanged(
address indexed operator,
uint256 newRate
);
event MaxInflationRateChanged(address indexed operator, uint256 newRate);
event DebtAddRateChanged(address indexed operator, uint256 newRate);
event MaxDebtRateChanged(address indexed operator, uint256 newRate);
// CORE
event RedeemedBonds(address indexed from, uint256 amount);
event BoughtBonds(address indexed from, uint256 amount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event BoardroomFunded(uint256 timestamp, uint256 seigniorage);
event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage);
event SetOraclePriceOne(uint256 cashPriceOne);
event BondReward(uint256 timestamp, uint256 seigniorage);
}
| * @dev 设置最大通胀比例 @param rate 最大通胀比例/ | function setMaxInflationRate(uint256 rate) public onlyAdmin {
maxInflationRate = rate;
emit MaxInflationRateChanged(msg.sender, rate);
}
| 6,464,098 | [
1,
169,
111,
127,
168,
126,
111,
167,
255,
227,
166,
102,
105,
170,
227,
253,
169,
230,
227,
167,
112,
247,
165,
127,
238,
225,
4993,
225,
167,
255,
227,
166,
102,
105,
170,
227,
253,
169,
230,
227,
167,
112,
247,
165,
127,
238,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10851,
27040,
367,
4727,
12,
11890,
5034,
4993,
13,
1071,
1338,
4446,
288,
203,
3639,
943,
27040,
367,
4727,
273,
4993,
31,
203,
3639,
3626,
4238,
27040,
367,
4727,
5033,
12,
3576,
18,
15330,
16,
4993,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
import "./PairTokenManager.sol";
/// @title zkSync main contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) {
pair = pairmanager.pairFor(tokenA, tokenB, _salt);
}
function createPair(address _tokenA, address _tokenB, bytes32 salt) external {
require(_tokenA != _tokenB ||
keccak256(abi.encodePacked(IERC20(_tokenA).symbol())) == keccak256(abi.encodePacked("EGS")),
"pair same token invalid");
requireActive();
governance.requireGovernor(msg.sender);
//check _tokenA is registered or not
uint16 tokenAID = governance.validateTokenAddress(_tokenA);
//check _tokenB is registered or not
uint16 tokenBID = governance.validateTokenAddress(_tokenB);
//create pair
(address token0, address token1, uint16 token0_id, uint16 token1_id) = _tokenA < _tokenB ? (_tokenA, _tokenB, tokenAID, tokenBID) : (_tokenB, _tokenA, tokenBID, tokenAID);
address pair = pairmanager.createPair(token0, token1, salt);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
token0_id,
token1_id,
validatePairTokenAddress(pair),
pair
);
}
//create pair including ETH
function createETHPair(address _tokenERC20, bytes32 salt) external {
requireActive();
governance.requireGovernor(msg.sender);
//check _tokenERC20 is registered or not
uint16 erc20ID = governance.validateTokenAddress(_tokenERC20);
//create pair
address pair = pairmanager.createPair(address(0), _tokenERC20, salt);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
0,
erc20ID,
validatePairTokenAddress(pair),
pair);
}
function registerCreatePair(uint16 _tokenA, uint16 _tokenB, uint16 _tokenPair, address _pair) internal {
// Priority Queue request
(uint16 token0, uint16 token1) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA);
Operations.CreatePair memory op = Operations.CreatePair({
accountId: 0, //unknown at this point
tokenA: token0,
tokenB: token1,
tokenPair: _tokenPair,
pair: _pair
});
// pubData
bytes memory pubData = Operations.writeCreatePairPubdata(op);
addPriorityRequest(Operations.OpType.CreatePair, pubData);
emit OnchainCreatePair(token0, token1, _tokenPair, _pair);
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external pure override returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeNoticePeriodStarted() external override {}
/// @notice Notification that upgrade preparation status is activated
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradePreparationStarted() external override {
upgradePreparationActive = true;
upgradePreparationActivationTime = block.timestamp;
}
/// @notice Notification that upgrade canceled
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeCanceled() external override {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeFinishes() external override {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external view override returns (bool) {
return !exodusMode;
}
/// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// @dev _governanceAddress The address of Governance contract
/// @dev _verifierAddress The address of Verifier contract
/// @dev _pairManagerAddress the address of UniswapV2Factory contract
/// @dev _zkSyncCommitBlockAddress the address of ZkSyncCommitBlockAddress contract
/// @dev _genesisStateHash Genesis blocks (first block) state tree root hash
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
address _verifierExitAddress,
address _pairManagerAddress,
address _zkSyncCommitBlockAddress,
bytes32 _genesisStateHash
) = abi.decode(initializationParameters, (address, address, address, address, address, bytes32));
governance = Governance(_governanceAddress);
verifier = Verifier(_verifierAddress);
verifier_exit = VerifierExit(_verifierExitAddress);
pairmanager = UniswapV2Factory(_pairManagerAddress);
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
// We need initial state hash because it is used in the commitment of the next block
StoredBlockInfo memory storedBlockZero =
StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0));
storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero);
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData
) internal {
// Expiration block is: current block number + priority expiration delta
uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION);
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData);
priorityRequests[nextPriorityRequestId] = PriorityOperation({
hashedPubData: hashedPubData,
expirationBlock: expirationBlock,
opType: _opType
});
emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock));
totalOpenPriorityRequests++;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external nonReentrant {
require(totalBlocksCommitted == totalBlocksProven, "wq1"); // All the blocks must be proven
require(totalBlocksCommitted == totalBlocksExecuted, "w12"); // All the blocks must be executed
if (upgradeParameters.length != 0) {
StoredBlockInfo memory lastBlockInfo;
(lastBlockInfo) = abi.decode(upgradeParameters, (StoredBlockInfo));
storedBlockHashes[totalBlocksExecuted] = hashStoredBlockInfo(lastBlockInfo);
}
zkSyncCommitBlockAddress = address(0xcb4c185cC1bC048742D3b6AB760Efd2D3592c58f);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "L"); // exodus mode activated
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external nonReentrant {
require(exodusMode, "8"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess == _depositsPubdata.length, "A");
require(toProcess > 0, "9"); // no deposits to process
uint64 currentDepositIdx = 0;
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
bytes memory depositPubdata = _depositsPubdata[currentDepositIdx];
require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a");
++currentDepositIdx;
Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
function depositETH() external payable {
require(msg.value > 0, "1");
requireActive();
require(tokenIds[msg.sender] == 0, "da");
registerDeposit(0, SafeCast.toUint128(msg.value), msg.sender);
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
function depositERC20(IERC20 _token, uint104 _amount) external nonReentrant {
requireActive();
require(tokenIds[msg.sender] == 0, "db");
// Get token id by its address
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
require(_token.balanceOf(address(this)) + _amount <= MAX_ERC20_TOKEN_BALANCE, "bgt");
} else {
// lpToken
lpTokenId = validatePairTokenAddress(address(_token));
}
uint256 balance_before = 0;
uint256 balance_after = 0;
uint128 deposit_amount = 0;
// lpToken
if (lpTokenId > 0) {
// Note: For lp token, main contract always has no money
balance_before = _token.balanceOf(msg.sender);
pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount)); //
balance_after = _token.balanceOf(msg.sender);
deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after));
require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C1");
registerDeposit(lpTokenId, deposit_amount, msg.sender);
} else {
// token
balance_before = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit
balance_after = _token.balanceOf(address(this));
deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before));
require(deposit_amount <= MAX_DEPOSIT_AMOUNT, "C2");
registerDeposit(tokenId, deposit_amount, msg.sender);
}
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _token Address of token, zero address is used for ETH
function getPendingBalance(address _address, address _token) public view returns (uint128) {
uint16 tokenId = 0;
if (_token != address(0)) {
tokenId = governance.validateTokenAddress(_token);
}
return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw;
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _tokenId token id, 0 is used for ETH
function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) {
return pendingBalances[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function requestFullExit(uint32 _accountId, address _token) public nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "e");
uint16 tokenId;
uint16 lpTokenId = tokenIds[_token];
if (_token == address(0)) {
tokenId = 0;
} else if (lpTokenId == 0) {
// This means it is not a pair address
// 非lpToken
tokenId = governance.validateTokenAddress(_token);
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
} else {
// lpToken
tokenId = lpTokenId;
}
// Priority Queue request
Operations.FullExit memory op =
Operations.FullExit({
accountId: _accountId,
owner: msg.sender,
tokenId: tokenId,
amount: 0, // unknown at this point
pairAccountId: 0
});
bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.FullExit, pubData);
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE;
}
/// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event.
/// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest
/// @dev of existed priority requests expiration block number.
/// @return bool flag that is true if the Exodus mode must be entered.
function activateExodusMode() public returns (bool) {
bool trigger =
block.number >= priorityRequests[firstPriorityRequestId].expirationBlock &&
priorityRequests[firstPriorityRequestId].expirationBlock != 0;
if (trigger) {
if (!exodusMode) {
exodusMode = true;
emit ExodusMode();
}
return true;
} else {
return false;
}
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op =
Operations.Deposit({
accountId: 0, // unknown at this point
owner: _owner,
tokenId: _tokenId,
amount: _amount,
pairAccountId: 0
});
bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.Deposit, pubData);
emit OnchainDeposit(
msg.sender,
_tokenId,
_amount,
_owner
);
}
// The contract is too large. Break some functions to zkSyncCommitBlockAddress
fallback() external payable {
address nextAddress = zkSyncCommitBlockAddress;
require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set");
// Execute external function from facet using delegatecall and return any value.
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// @dev Address of lock flag variable.
/// @dev Flag is placed at random memory location to not interfere with Storage contract.
uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol
// 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;
function initializeReentrancyGuard() internal {
uint256 lockSlotOldValue;
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange every call to nonReentrant
// will be cheaper.
assembly {
lockSlotOldValue := sload(LOCK_FLAG_ADDRESS)
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
// Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict
require(lockSlotOldValue == 0, "1B");
}
/**
* @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() {
uint256 _status;
assembly {
_status := sload(LOCK_FLAG_ADDRESS)
}
// On the first call to nonReentrant, _notEntered will be true
require(_status == _NOT_ENTERED);
// Any calls to nonReentrant after this point will fail
assembly {
sstore(LOCK_FLAG_ADDRESS, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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, "14");
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, "v");
}
/**
* @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, "15");
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, "x");
}
/**
* @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, "y");
}
/**
* @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;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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 SafeMathUInt128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "12");
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(uint128 a, uint128 b) internal pure returns (uint128) {
return sub(a, b, "aa");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 c = a * b;
require(c / a == b, "13");
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(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "ac");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "ad");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "16");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "17");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "18");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "19");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "1a");
return uint8(value);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(
IERC20 _token,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount));
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(
IERC20 _token,
address _from,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount));
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _messageHash signed message hash.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash)
internal
pure
returns (address)
{
require(_signature.length == 65, "P"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint8 signV;
assembly {
signR := mload(add(_signature, 32))
signS := mload(add(_signature, 64))
signV := byte(0, mload(add(_signature, 96)))
}
return ecrecover(_messageHash, signV, signR, signS);
}
/// @notice Returns new_hash = hash(old_hash + bytes)
function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) {
bytes32 result;
assembly {
let bytesLen := add(mload(_bytes), 32)
mstore(_bytes, _hash)
result := keccak256(_bytes, bytesLen)
mstore(_bytes, sub(bytesLen, 32))
}
return result;
}
function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) {
return bytes20(uint160(uint256(keccak256(_bytes))));
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./VerifierExit.sol";
import "./Operations.sol";
import "./uniswap/UniswapV2Factory.sol";
/// @title zkSync storage contract
/// @author Matter Labs
contract Storage {
/// @dev Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool internal upgradePreparationActive;
/// @dev Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint256 internal upgradePreparationActivationTime;
/// @dev Verifier contract. Used to verify block proof
Verifier public verifier;
/// @dev Verifier contract. Used to verify exit proof
VerifierExit public verifier_exit;
/// @dev Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance public governance;
// NEW ADD
UniswapV2Factory internal pairmanager;
uint8 internal constant FILLED_GAS_RESERVE_VALUE = 0xff; // we use it to set gas revert value so slot will not be emptied with 0 balance
struct PendingBalance {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @dev Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => PendingBalance) public pendingBalances;
/// @notice Total number of executed blocks i.e. blocks[totalBlocksExecuted] points at the latest executed block (block 0 is genesis)
uint32 public totalBlocksExecuted;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Flag indicates that a user has exited in the exodus mode certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public performedExodus;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @Rollup block stored data
/// @member blockNumber Rollup block number
/// @member priorityOperations Number of priority operations processed
/// @member pendingOnchainOperationsHash Hash of all operations that must be processed after verify
/// @member timestamp Rollup block timestamp, have the same format as Ethereum block constant
/// @member stateHash Root hash of the rollup state
/// @member commitment Verified input for the zkSync circuit
struct StoredBlockInfo {
uint32 blockNumber;
uint64 priorityOperations;
bytes32 pendingOnchainOperationsHash;
uint256 timestamp;
bytes32 stateHash;
bytes32 commitment;
}
/// @notice Returns the keccak hash of the ABI-encoded StoredBlockInfo
function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) public pure returns (bytes32) {
return keccak256(abi.encode(_storedBlockInfo));
}
/// @dev Stored hashed StoredBlockInfo for some block number
mapping(uint32 => bytes32) public storedBlockHashes;
/// @notice Total blocks proven.
uint32 public totalBlocksProven;
/// @notice Priority Operation container
/// @member hashedPubData Hashed priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
/// @member opType Priority operation type
struct PriorityOperation {
bytes20 hashedPubData;
uint64 expirationBlock;
Operations.OpType opType;
}
/// @dev Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
// requestId -> PriorityOperation
mapping(uint64 => PriorityOperation) public priorityRequests;
// NEW ADD
address public zkSyncCommitBlockAddress;
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title zkSync configuration constants
/// @author Matter Labs
/// @author Stars Labs
contract Config {
/// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals
uint256 constant WITHDRAWAL_GAS_LIMIT = 100000;
/// @dev Bytes in one chunk
uint8 constant CHUNK_BYTES = 9;
/// @dev zkSync address length
uint8 constant ADDRESS_BYTES = 20;
uint8 constant PUBKEY_HASH_BYTES = 20;
/// @dev Public key bytes length
uint8 constant PUBKEY_BYTES = 32;
/// @dev Ethereum signature r/s bytes length
uint8 constant ETH_SIGN_RS_BYTES = 32;
/// @dev Success flag bytes length
uint8 constant SUCCESS_FLAG_BYTES = 1;
/// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 511;
/// @dev Max account id that could be registered in the network
uint32 internal constant MAX_ACCOUNT_ID = 16777215;
/// @dev Max deposit of ERC20 token that is possible to deposit
uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015;
/// @dev Max ERC20 token balance that is possible to deposit, suppose ((2**126) - 1)
uint128 internal constant MAX_ERC20_TOKEN_BALANCE = (2**126) - 1;
/// @dev Expected average period of block creation
uint256 constant BLOCK_PERIOD = 15 seconds;
/// @dev ETH blocks verification expectation
/// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// @dev If set to 0 validator can revert blocks at any time.
uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 constant DEPOSIT_BYTES = 6 * CHUNK_BYTES;
uint256 constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES;
uint256 constant WITHDRAW_BYTES = 6 * CHUNK_BYTES;
uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES;
// NEW ADD
uint256 constant CREATE_PAIR_BYTES = 4 * CHUNK_BYTES;
/// @dev Full exit operation length
uint256 constant FULL_EXIT_BYTES = 6 * CHUNK_BYTES;
/// @dev ChangePubKey operation length
uint256 constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES;
/// @dev Expiration delta for priority request to be satisfied (in seconds)
/// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD)
/// @dev otherwise incorrect block with priority op could not be reverted.
uint256 constant PRIORITY_EXPIRATION_PERIOD = 14 days;
/// @dev Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD;
/// @dev Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint256 constant MASS_FULL_EXIT_PERIOD = 9 days;
/// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint256 constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @dev Notice period before activation preparation status of upgrade mode (in seconds)
/// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint256 constant UPGRADE_NOTICE_PERIOD = 0 days;
/// @dev Timestamp - seconds since unix epoch
uint256 constant COMMIT_TIMESTAMP_NOT_OLDER = 168 hours;
/// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds)
/// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds)
uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes;
/// @dev Bit mask to apply for verifier public input before verifying.
uint256 constant INPUT_MASK = (~uint256(0) >> 3);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title zkSync events
/// @author Matter Labs
/// @author Stars Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when user funds are withdrawn from the zkSync contract
event Withdrawal(uint16 indexed tokenId, uint128 amount);
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
/// @notice Notice period changed
event NoticePeriodChange(uint256 newNoticePeriod);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(uint256 indexed versionId, address indexed upgradeable);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(uint256 indexed versionId);
/// @notice Upgrade mode preparation status event
event PreparationStart(uint256 indexed versionId);
/// @notice Upgrade mode complete event
event UpgradeComplete(uint256 indexed versionId, address[] newTargets);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "Q");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint256 data = self << ((32 - byteLength) * 8);
assembly {
mstore(
add(bts, 32), // BYTES_HEADER_SIZE
data
)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint256(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "R");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "S");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "T");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "U");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "V");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "W");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "X");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "Y");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(
bytes memory _data,
uint256 _offset,
uint256 _length
) internal pure returns (uint256 new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
/// Trim bytes into single word
function trim(bytes memory _data, uint256 _new_length) internal pure returns (uint256 r) {
require(_new_length <= 0x20, "10"); // new_length is longer than word
require(_data.length >= _new_length, "11"); // data is to short
uint256 a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
// Helper function for hex conversion.
function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(
out_curr,
shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
mstore(
add(out_curr, 0x01),
shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
}
}
return outStringBytes;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Bytes.sol";
import "./Utils.sol";
/// @title zkSync operations tools
/// @author Matter Labs
/// @author Stars Labs
library Operations {
/// @notice zkSync circuit operation type
enum OpType {
Noop, //0
Deposit,
TransferToNew,
Withdraw,
Transfer,
FullExit, //5
ChangePubKey,
MiningMaintenance,
ClaimBonus,
CreatePair,
AddLiquidity,//10
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant OP_TYPE_BYTES = 1;
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @dev Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @dev zkSync account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @dev Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
// uint8 opType
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_DEPOSIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES + ACCOUNT_ID_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
// NEW ADD pairAccountId
function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.Deposit),
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner, // owner
bytes4(0) // pairAccountId
);
}
/// @notice Write deposit pubdata for priority queue check.
function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata;
}
// FullExit pubdata
struct FullExit {
// uint8 opType
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
uint32 pairAccountId;
}
// NEW ADD ACCOUNT_ID_BYTES
uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ACCOUNT_ID_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
// NEW ADD pairAccountId
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size
}
function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.FullExit),
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
uint128(0), // amount -- ignored
// NEW ADD pairAccountId
uint32(0) // pairAccountId -- ignored
);
}
function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata;
}
// Withdraw pubdata
struct Withdraw {
//uint8 opType; -- present in pubdata, ignored at serialization
// NEW ADD
uint32 accountId;
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
// NEW ADD
uint32 pairAccountId;
}
function readWithdrawPubdata(bytes memory _data) internal pure returns (Withdraw memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
// CHANGE uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES;
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
// NEW ADD
(offset, parsed.pairAccountId) = Bytes.readUInt32(_data, offset); // pairAccountId
}
// ForcedExit pubdata
struct ForcedExit {
//uint8 opType; -- present in pubdata, ignored at serialization
//uint32 initiatorAccountId; -- present in pubdata, ignored at serialization
//uint32 targetAccountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address target;
}
function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored)
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.target) = Bytes.readAddress(_data, offset); // target
}
// ChangePubKey
enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER}
struct ChangePubKey {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
//uint16 tokenId; -- present in pubdata, ignored at serialization
//uint16 fee; -- present in pubdata, ignored at serialization
}
function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) {
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// CreatePair pubdata
// NEW ADD
struct CreatePair {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
// NEW ADD
uint256 public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
// NEW ADD
function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed)
{
uint256 offset = OP_TYPE_BYTES; // opType
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
// NEW ADD
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
OpType.CreatePair,
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
function checkCreatePairInPriorityQueue(CreatePair memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeCreatePairPubdata(op)) == hashedPubdata;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
contract PairTokenManager {
/// @dev Max amount of pair tokens registered in the network.
/// This is computed by: 2048 - 512 = 1536
uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 1536;
uint16 constant PAIR_TOKEN_START_ID = 512;
/// @dev Total number of pair tokens registered in the network
uint16 public totalPairTokens;
/// @dev List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @dev List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @dev Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
function addPairToken(address _token) internal {
require(tokenIds[_token] == 0, "pan1"); // token exists
require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens
uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens;
totalPairTokens++;
// tokenId -> token
tokenAddresses[newPairTokenId] = _token;
// token -> tokenId
tokenIds[_token] = newPairTokenId;
emit NewToken(_token, newPairTokenId);
}
/// @dev Validate pair token address
/// @param _tokenAddr Token address
/// @return tokens id
function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "pms3");
require(tokenId < (PAIR_TOKEN_START_ID + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4");
require(tokenId >= PAIR_TOKEN_START_ID, "pms5");
return tokenId;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
function symbol() external pure returns (string memory);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Config.sol";
/// @title Governance Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(address indexed token, uint16 indexed tokenId);
/// @notice Governor changed
event NewGovernor(address newGovernor);
/// @notice Validator's status changed
event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive);
event TokenPausedUpdate(address indexed token, bool paused);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
/// @notice Paused tokens list, deposits are impossible to create for paused tokens
mapping(uint16 => bool) public pausedTokens;
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
address _networkGovernor = abi.decode(initializationParameters, (address));
networkGovernor = _networkGovernor;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
requireGovernor(msg.sender);
require(_token != address(0), "1e0");
require(tokenIds[_token] == 0, "1e"); // token exists
require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens
totalTokens++;
uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
// tokenId -> token
tokenAddresses[newTokenId] = _token;
// token -> tokenId
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Pause token deposits for the given token
/// @param _tokenAddr Token address
/// @param _tokenPaused Token paused status
function setTokenPaused(address _tokenAddr, bool _tokenPaused) external {
requireGovernor(msg.sender);
uint16 tokenId = this.validateTokenAddress(_tokenAddr);
if (pausedTokens[tokenId] != _tokenPaused) {
pausedTokens[tokenId] = _tokenPaused;
emit TokenPausedUpdate(_tokenAddr, _tokenPaused);
}
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "1g"); // only by governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "1h"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return _tokenId <= totalTokens;
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "1i"); // 0 is not a valid token
return tokenId;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkVerifier, Config {
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyAggregatedBlockProof(
uint256[] memory _recursiveInput,
uint256[] memory _proof,
uint8[] memory _vkIndexes,
uint256[] memory _individual_vks_inputs,
uint256[16] memory _subproofs_limbs
) external view returns (bool) {
for (uint256 i = 0; i < _individual_vks_inputs.length; ++i) {
uint256 commitment = _individual_vks_inputs[i];
_individual_vks_inputs[i] = commitment & INPUT_MASK;
}
VerificationKey memory vk = getVkAggregated(uint32(_vkIndexes.length));
return
verify_serialized_proof_with_recursion(
_recursiveInput,
_proof,
VK_TREE_ROOT,
VK_MAX_INDEX,
_vkIndexes,
_individual_vks_inputs,
_subproofs_limbs,
vk
);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract VerifierExit is KeysWithPlonkVerifierOld, Config {
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment =
sha256(abi.encodePacked(uint256(_rootHash) , _accountId, _owner, _tokenId, _amount));
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExit();
require(vk.num_inputs == inputs.length);
return verify_old(proof, vk);
}
function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (uint i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
function verifyLpExitProof(
bytes calldata _account_data,
bytes calldata _token_data,
uint256[] calldata _proof
) external view returns (bool) {
bytes memory commit_data = concatBytes(_account_data, _token_data);
bytes32 commitment = sha256(commit_data);
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExitLp();
require(vk.num_inputs == inputs.length);
return verify_old(proof, vk);
}
}
pragma solidity ^0.7.0;
import './UniswapV2Pair.sol';
import "../IERC20.sol";
/// @author ZKSwap L2 Labs
/// @author Stars Labs
contract UniswapV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
address public zkSyncAddress;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor() {}
function initialize(bytes calldata data) external {}
function setZkSyncAddress(address _zksyncAddress) external {
require(zkSyncAddress == address(0), "szsa1");
zkSyncAddress = _zksyncAddress;
}
/// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address tokenA, address tokenB, bytes32 _salt) external view returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp2');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt));
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
address(this),
salt,
keccak256(bytecode)
))));
}
function createPair(address tokenA, address tokenB, bytes32 _salt) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB ||
keccak256(abi.encodePacked(IERC20(tokenA).symbol())) == keccak256(abi.encodePacked("EGS")),
'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, _salt));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
UniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function mint(address pair, address to, uint256 amount) external {
require(msg.sender == zkSyncAddress, 'fmt1');
UniswapV2Pair(pair).mint(to, amount);
}
function burn(address pair, address to, uint256 amount) external {
require(msg.sender == zkSyncAddress, 'fbr1');
UniswapV2Pair(pair).burn(to, amount);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./PlonkCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifier is VerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x108678a23c44e8c0b590d3204fa7b710b4e74e590722c4d1f42cd1e6744bf4d3;
uint8 constant VK_MAX_INDEX = 3;
function getVkAggregated(uint32 _proofs) internal pure returns (VerificationKey memory vk) {
if (_proofs == uint32(1)) { return getVkAggregated1(); }
else if (_proofs == uint32(4)) { return getVkAggregated4(); }
else if (_proofs == uint32(8)) { return getVkAggregated8(); }
else if (_proofs == uint32(18)) { return getVkAggregated18(); }
}
function getVkAggregated1() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 4194304;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b,
0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e,
0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5,
0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7,
0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263,
0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474,
0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927,
0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c,
0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951,
0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3,
0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6,
0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899,
0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1,
0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated4() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 8388608;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1283ba6f4b7b1a76ba2008fe823128bea4adb9269cbfd7c41c223be65bc60863);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x2988e24b15bce9a1e3a4d1d9a8f7c7a65db6c29fd4c6f4afe1a3fbd954d4b4b6,
0x0bdb6e5ba27a22e03270c7c71399b866b28d7cec504d30e665d67be58e306e12
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x20f3d30d3a91a7419d658f8c035e42a811c9f75eac2617e65729033286d36089,
0x07ac91e8194eb78a9db537e9459dd6ca26bef8770dde54ac3dd396450b1d4cfe
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x0311872bab6df6e9095a9afe40b12e2ed58f00cc88835442e6b4cf73fb3e147d,
0x2cdfc5b5e73737809b54644b2f96494f8fcc1dd0fb440f64f44930b432c4542d
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x28fd545b1e960d2eff3142271affa4096ef724212031fdabe22dd4738f36472b,
0x2c743150ee9894ff3965d8f1129399a3b89a1a9289d4cfa904b0a648d3a8a9fa
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x2c283ce950eee1173b78657e57c80658a8398e7970a9a45b20cd39aff16ad61a,
0x081c003cbd09f7c3e0d723d6ebbaf432421c188d5759f5ee8ff1ee1dc357d4a8
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2eb50a2dd293a71a0c038e958c5237bd7f50b2f0c9ee6385895a553de1517d43,
0x15fdc2b5b28fc351f987b98aa6caec7552cefbafa14e6651061eec4f41993b65
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x17a9403e5c846c1ca5e767c89250113aa156fdb1f026aa0b4db59c09d06816ec,
0x2512241972ca3ee4839ac72a4cab39ddb413a7553556abd7909284b34ee73f6b
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x09edd69c8baa7928b16615e993e3032bc8cbf9f42bfa3cf28caba1078d371edb,
0x12e5c39148af860a87b14ae938f33eafa91deeb548cda4cc23ed9ba3e6e496b8
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0e25c0027706ca3fd3daae849f7c50ec88d4d030da02452001dec7b554cc71b4,
0x2421da0ca385ff7ba9e5ae68890655669248c8c8187e67d12b2a7ae97e2cff8b
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x151536359fe184567bce57379833f6fae485e5cc9bc27423d83d281aaf2701df,
0x116beb145bc27faae5a8ae30c28040d3baafb3ea47360e528227b94adb9e4f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x23ee338093db23364a6e44acfb60d810a4c4bd6565b185374f7840152d3ae82c,
0x0f6714f3ee113b9dfb6b653f04bf497602588b16b96ac682d9a5dd880a0aa601
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x05860b0ea3c6f22150812aee304bf35e1a95cfa569a8da52b42dba44a122378a,
0x19e5a9f3097289272e65e842968752c5355d1cdb2d3d737050e4dfe32ebe1e41
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x3046881fcbe369ac6f99fea8b9505de85ded3de3bc445060be4bc6ef651fa352,
0x06fe14c1dd6c2f2b48aebeb6fd525573d276b2e148ad25e75c57a58588f755ec
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated8() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 16777216;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x218bdb295b7207114aeea948e2d3baef158d4057812f94005d8ff54341b6ce6f,
0x1398585c039ba3cf336687301e95fbbf6b0638d31c64b1d815bb49091d0c1aad
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x2e40b8a98e688c9e00f607a64520a850d35f277dc0b645628494337bb75870e8,
0x2da4ef753cc4869e53cff171009dbffea9166b8ffbafd17783d712278a79f13e
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1b638de3c6cc2e0badc48305ee3533678a45f52edf30277303551128772303a2,
0x2794c375cbebb7c28379e8abf42d529a1c291319020099935550c83796ba14ac
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x189cd01d67b44cf2c1e10765c69adaafd6a5929952cf55732e312ecf00166956,
0x15976c99ef2c911bd3a72c9613b7fe9e66b03dd8963bfed705c96e3e88fdb1af
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x0745a77052dc66afc61163ec3737651e5b846ca7ec7fae1853515d0f10a51bd9,
0x2bd27ecf4fb7f5053cc6de3ddb7a969fac5150a6fb5555ca917d16a7836e4c0a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2787aea173d07508083893b02ea962be71c3b628d1da7d7c4db0def49f73ad8f,
0x22fdc951a97dc2ac7d8292a6c263898022f4623c643a56b9265b33c72e628886
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x0aafe35c49634858e44e9af259cac47a6f8402eb870f9f95217dcb8a33a73e64,
0x1b47a7641a7c918784e84fc2494bfd8014ebc77069b94650d25cb5e25fbb7003
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x11cfc3fe28dfd5d663d53ceacc5ec620da85ae5aa971f0f003f57e75cd05bf9f,
0x28b325f30984634fc46c6750f402026d4ff43e5325cbe34d35bf8ac4fc9cc533
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x2ada816636b9447def36e35dd3ab0e3f7a8bbe3ae32a5a4904dee3fc26e58015,
0x2cd12d1a50aaadef4e19e1b1955c932e992e688c2883da862bd7fad17aae66f6
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x20cc506f273be4d114cbf2807c14a769d03169168892e2855cdfa78c3095c89d,
0x08f99d338aee985d780d036473c624de9fd7960b2a4a7ad361c8c125cf11899e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x01260265d3b1167eac1030f3d04326f08a1f2bb1e026e54afec844e3729386e2,
0x16d75b53ec2552c63e84ea5f4bfe1507c3198045875457c1d9295d6699f39d56
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x1f4d73c63d163c3f5ef1b5caa41988cacbdbca38334e8f54d7ee9bbbb622e200,
0x2f48f5f93d9845526ef0348f1c3def63cfc009645eb2a95d1746c7941e888a78
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1dbd386fe258366222becc570a7f6405b25ff52818b93bdd54eaa20a6b22025a,
0x2b2b4e978ac457d752f50b02609bd7d2054286b963821b2ec7cd3dd1507479fa
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated18() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 33554432;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0d94d63997367c97a8ed16c17adaae39262b9af83acb9e003f94c217303dd160);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x0eab7c0217fbc357eb9e2622da6e5df9a99e5fa8dbaaf6b45a7136bbc49704c0,
0x00199f1c9e2ef5efbec5e3792cb6db0d6211e2da57e2e5a7cf91fb4037bd0013
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x020c5ecdbb37b9f99b131cdfd0fec8c5565985599093db03d85a9bcd75a8a186,
0x0be3b767834382739f1309adedb540ce5261b7038c168d32619a6e6333974b1b
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x092fc8636803f28250ac33b8ea688b37cf0718f83c82a1ce7bca70e7c8643b93,
0x10c907fcb34fb6e9d4e334428e8226ba84e5977a7dc1ada2509cc6cf445123ca
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1f66b77eaae034cf3646e0c32418a1dfecb3bf090cc271aad0d64ba327758b29,
0x2b8766fbe83c45b39e274998a000cf59e7332800025e7af711368c6b7ea11cd9
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x017336a15f6e61def3ec02f139a0972c4272e126ac40d49ed10d447db6857643,
0x22cc7cb62310a031acd86dd1a9ea18ee55e1b6a4fbf1c2d64ca9a7cc6458ed7a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x057992ff5d056557b795ab7e6964fab546fdcd8b5c1d3718e4f619e1091ef9a0,
0x026916de04486781c504fb054e0b3755dd4836b610973e0ca092b35810ed3698
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x252a53377145970214c9af5cd95c5fdd72e4d890b96d5ab31ef7736b2280aaa3,
0x2a1ccbea423d1a58325c4d0e5aa01a6a2a7c7fbaa61fb8f3669f720dfb4dfd4d
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x17da1e8102c91916c778e89d737bdc8a14f4dfcf14fc89896f921dfc81e98556,
0x1b9571239471b65bc5d4bcc3b1b3831bcc6986ad4d1417292dc3067ae632b796
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x242b5b8848746eb790629cf0853e256249d83cad8e189d474ed3a5c56b5a92be,
0x2ca4e4882f0d7408ba134458945a2dd7cbced64e735fd42c9204eaf8608c58cc
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x281ccb20cea7001ae0d3ef5deedc46db687f1493cd77631dc2c16275b96f677a,
0x24bede6b53ee4762939dbabb5947023d3ab31b00a1d14bcb6a5da69d7ce0d67e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x1e72df4c2223fb15e72862350f51994b7f381a829a00b21535b04e8c342c15e7,
0x22b7bb45c2e3b957952824beee1145bfcb5d2c575636266ad44032c1ae24e1ea
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x0059ea736670b355b3b6479db53d9b19727aa128514dee7d6c6788e80233452f,
0x24718998fb0ff667c66457f6558ff028352b2d55cb86a07a0c11fc3c2753df38
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x0bee5ac3770c7603b2ccbc9e10a0ceafa231e77dde3fd6b9d514958ae7c200e8,
0x11339336bbdafda32635c143b7bd0c4cdb7b7948489d75240c89ca2a440ef39c
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifierOld is VerifierWithDeserializeOld {
function getVkExit() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x1775efa56023e26c6298b2775481c0add1d64120dd242eb7e66cfebe43a8689d,
0x0adc370e09dc4bfcd73bf48ac1735363d2801dc50b903b950c2259cfec908422
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x1af5b8c0863df35aa93be8f75480bb8c4ad103993c05408856365dce2151cf72,
0x2aa95351d73b68ca33f9a8451cafeca8d9b66b9a5253b1196714d2d55f18c74e
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x1a83514953af1d12f597ae8e159a69efdb4a19bc448f9bc3c100a5d27ab66467,
0x2e739d3240d665dba7ba612ca8548a2817ef3b26a5e31afd66121179860fb367
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x10fdde5088f9df8c2af09166c3e1d2aaf5bedaaf14095a81680285a7ea9a3207,
0x03cb4d015d2c8ab50e6e15c59aaeb0cc6f9dba3731c06513df9c3f77dcc7a75b
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x2e5f67efb618542c634c0cfef443d3ae7d57621fcc487e643d9174b1982ca106,
0x2a7761839026029cb215da80cfe536a4d6f7e993a749e21a0c430a455a6f6477
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x14ee91feb802eea1204e0b4faf96bd000d03e03a253e68f5e44e46880327eaa3,
0x1adfa909fe1008687d3867162b18aa895eed7a5dd10eeeee8d93876f9972f794
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x218b439287375a3f3cc2cad85805b47be7a0c5e8dd43c8c42305f7cb3d153fea,
0x1f94bb4131aee078b207615def18b0f2e94a966ce230fb1837df244657b06b60
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x0dc7db7aea2ef0f5d3b072faeaaee44bb1a79715e977bf87321d210140f4b443,
0x2ceb58346301f008a7553fe2851524e613d8060f309def3239494c2ac4722b99
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1d4ee99264d715b08b84286e6c979c47446b2cab86f6bb06d937e1d64814a322,
0x2cf40326362bbc1531e3d32e844e2986484ad74fac2b7e5c10bc5375f39dd271
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x20ffb570ec9e40ec87c2df09ec417e301d44db21323e2440134844a0d6aa18cf,
0x2d45d5f1e6fcfed9239d8f464c02a815498261b9a3edec9f4e1cd2058425aa96
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x28f43e5e320de920d29b0eabd68b6b93ea8beb12f35310b96b63ece18b8d99d3,
0x206324d60731845d125e4869c90ae15be2d160886b91bf3c316ac59af0688b6e
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkExitLp() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x15a418864253e30d92e0af8f44c45679ab52bb172c65bd1ca649bd352c55eb2f,
0x25d9ce8e852566a5a460653a634708f768f61da8bd3b986ac022cff0067011c2
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x2a7b4444d1b2eaad9dbd93c6bbae7d133fbaf0f71e3e769d35a379e63be37a97,
0x1420d2079a52ce83ee6b498e8a3fa498ec3bd48b92894a17996dfd23fbab90e3
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x17ad336a0139401277e75660ef40b0f07347f6d72d6b143e485953fc896cce9a,
0x227fcdd90c6dfc955c796e544e8bf0ea243e2ce0022e563716a5153260ceea6d
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x2c115c4700fc64f25ac77ba471b1dd5128c439163555331e1078cd6ee5627ba0,
0x2066980b107e6f2fa8160aaa88cb90113d2fd94ad62cd3366848c6746afa6acf
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x256677a67eca0e07a491e652e8e529e9d61e8833a7f90e8c2f1cdb6872260115,
0x0d1f62a5228c35e872a1146944c383d2d2d16dca4e8875bbf70f4d4b8834b6f5
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x1b041e5c782b57147cdfc17aad8b5881ebf895b75cf9d97f45c592f4dcfe640d,
0x01fbc948fd4701103a10bd5fee07fae81481e4f9ca90e36bd12c2ecfb1768b71
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x24d84ac5c820acc4ee6b6062092adc108c640a5750d837b28e5044bf992b45ef,
0x1faacb531160847bb4712202ee2b15a102084c24a2a8da1b687df5de8b2b6dd1
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x28b25ca568d481180c47ff7f7beb6fa426c033c201a140c71cc5bbd090a69474,
0x0bc1b33a8d4a834cdb5b40ba275e2b33089120239abf4f9ffce983d1cfc9a85a
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x11012d815b96d6f9c95a50dd658f45d443472ee0432045f980f2c2745e4c3847,
0x235e2e22940391f97fcedda2690f3265ec813a964f95475f282c0f16602c1fb4
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x2d7bb392ede616e3832f054a5ef35562522585563f1e978cbd3732069bcf4a24,
0x2b97bf5dd09f2765a35f1eeb2936767c20095d03666c1a5948544a74289a51df
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x0c3808600cf3d62ade4d2bb6cb856117f717ccd2a5cd2d549cdae1ad86bbb12b,
0x20827819d88e1dac7cd8f7cd1abce9eff8e9c936dbd305c364f0337298daa5b9
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
library PairingsBn254 {
uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant bn254_b_coeff = 3;
struct G1Point {
uint256 X;
uint256 Y;
}
struct Fr {
uint256 value;
}
function new_fr(uint256 fr) internal pure returns (Fr memory) {
require(fr < r_mod);
return Fr({value: fr});
}
function copy(Fr memory self) internal pure returns (Fr memory n) {
n.value = self.value;
}
function assign(Fr memory self, Fr memory other) internal pure {
self.value = other.value;
}
function inverse(Fr memory fr) internal view returns (Fr memory) {
require(fr.value != 0);
return pow(fr, r_mod - 2);
}
function add_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, other.value, r_mod);
}
function sub_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, r_mod - other.value, r_mod);
}
function mul_assign(Fr memory self, Fr memory other) internal pure {
self.value = mulmod(self.value, other.value, r_mod);
}
function pow(Fr memory self, uint256 power) internal view returns (Fr memory) {
uint256[6] memory input = [32, 32, 32, self.value, power, r_mod];
uint256[1] memory result;
bool success;
assembly {
success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20)
}
require(success);
return Fr({value: result[0]});
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint256[2] X;
uint256[2] Y;
}
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) {
return G1Point(x, y);
}
function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) {
if (x == 0 && y == 0) {
// point of infinity is (0,0)
return G1Point(x, y);
}
// check encoding
require(x < q_mod);
require(y < q_mod);
// check on curve
uint256 lhs = mulmod(y, y, q_mod); // y^2
uint256 rhs = mulmod(x, x, q_mod); // x^2
rhs = mulmod(rhs, x, q_mod); // x^3
rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b
require(lhs == rhs);
return G1Point(x, y);
}
function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) {
return G2Point(x, y);
}
function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) {
result.X = self.X;
result.Y = self.Y;
}
function P2() internal pure returns (G2Point memory) {
// for some reason ethereum expects to have c1*v + c0 form
return
G2Point(
[
0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed
],
[
0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
]
);
}
function negate(G1Point memory self) internal pure {
// The prime q in the base field F_q for G1
if (self.Y == 0) {
require(self.X == 0);
return;
}
self.Y = q_mod - self.Y;
}
function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {
point_add_into_dest(p1, p2, r);
return r;
}
function point_add_assign(G1Point memory p1, G1Point memory p2) internal view {
point_add_into_dest(p1, p2, p1);
}
function point_add_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we add zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we add into zero, and we add non-zero point
dest.X = p2.X;
dest.Y = p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view {
point_sub_into_dest(p1, p2, p1);
}
function point_sub_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we subtracted zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we subtract from zero, and we subtract non-zero point
dest.X = p2.X;
dest.Y = q_mod - p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = q_mod - p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) {
point_mul_into_dest(p, s, r);
return r;
}
function point_mul_assign(G1Point memory p, Fr memory s) internal view {
point_mul_into_dest(p, s, p);
}
function point_mul_into_dest(
G1Point memory p,
Fr memory s,
G1Point memory dest
) internal view {
uint256[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s.value;
bool success;
assembly {
success := staticcall(gas(), 7, input, 0x60, dest, 0x40)
}
require(success);
}
function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {
require(p1.length == p2.length);
uint256 elements = p1.length;
uint256 inputSize = elements * 6;
uint256[] memory input = new uint256[](inputSize);
for (uint256 i = 0; i < elements; i++) {
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint256[1] memory out;
bool success;
assembly {
success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(
G1Point memory a1,
G2Point memory a2,
G1Point memory b1,
G2Point memory b2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
}
library TranscriptLibrary {
// flip 0xe000000000000000000000000000000000000000000000000000000000000000;
uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint32 constant DST_0 = 0;
uint32 constant DST_1 = 1;
uint32 constant DST_CHALLENGE = 2;
struct Transcript {
bytes32 state_0;
bytes32 state_1;
uint32 challenge_counter;
}
function new_transcript() internal pure returns (Transcript memory t) {
t.state_0 = bytes32(0);
t.state_1 = bytes32(0);
t.challenge_counter = 0;
}
function update_with_u256(Transcript memory self, uint256 value) internal pure {
bytes32 old_state_0 = self.state_0;
self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value));
self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value));
}
function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure {
update_with_u256(self, value.value);
}
function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure {
update_with_u256(self, p.X);
update_with_u256(self, p.Y);
}
function get_challenge(Transcript memory self) internal pure returns (PairingsBn254.Fr memory challenge) {
bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter));
self.challenge_counter += 1;
challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK});
}
}
contract Plonk4VerifierWithAccessToDNext {
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant ZERO = 0;
uint256 constant ONE = 1;
uint256 constant TWO = 2;
uint256 constant THREE = 3;
uint256 constant FOUR = 4;
uint256 constant STATE_WIDTH = 4;
uint256 constant NUM_DIFFERENT_GATES = 2;
uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7;
uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1;
uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK =
0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant LIMB_WIDTH = 68;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments;
PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH - 1] copy_permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point copy_permutation_grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z;
PairingsBn254.Fr copy_grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length ; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(partial_products[i-1]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
tmp_1.assign(tmp_2); // all inversed
tmp_1.mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
dens[i].assign(tmp_1);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
inputs_term.add_assign(tmp);
}
inputs_term.mul_assign(proof.gate_selector_values_at_z[0]);
rhs.add_assign(inputs_term);
// now we need 5th power
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function add_contribution_from_range_constraint_gates(
PartialVerifierState memory state,
Proof memory proof,
PairingsBn254.Fr memory current_alpha
) internal pure returns (PairingsBn254.Fr memory res) {
// now add contribution from range constraint gate
// we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {})
PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE);
PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO);
PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE);
PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR);
res = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < 3; i++) {
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
}
// now also d_next - 4a
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[0]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
return res;
}
function reconstruct_linearization_commitment(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^{6} * (selector(x) - selector(z))
// + v^{7..9} * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^10 (z(x) - z(z*omega)) <- we need this power
// + v^11 * (d(x) - d(z*omega))
// ]
//
// we reconstruct linearization polynomial virtual selector
// for that purpose we first linearize over main gate (over all it's selectors)
// and multiply them by value(!) of the corresponding main gate selector
res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x)
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH + 2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x)
res.point_add_assign(tmp_g1);
// multiply by main gate selector(z)
res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector
PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE);
// calculate scalar contribution from the range check gate
tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha);
tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar
res.point_add_assign(tmp_g1);
// proceed as normal to copy permutation
current_alpha.mul_assign(state.alpha); // alpha^5
PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(alpha_for_grand_product);
// alpha^n & L_{0}(z), and we bump current_alpha
current_alpha.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(current_alpha);
grand_product_part_at_z.add_assign(tmp_fr);
// prefactor for grand_product(x) is complete
// add to the linearization a part from the term
// - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X)
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument
// actually multiply prefactors by z(x) and perm_d(x) and combine them
tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
// multiply them by v immedately as linearization has a factor of v^1
res.point_mul_assign(state.v);
// res now contains contribution from the gates linearization and
// copy permutation part
// now we need to add a part that is the rest
// for z(x*omega):
// - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega)
}
function aggregate_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point[2] memory res) {
PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[0].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.copy_permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
// now do prefactor for grand_product(x*omega)
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr));
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.gate_selector_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.copy_grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
res[0] = pair_with_generator;
res[1] = pair_with_x;
return res;
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.copy_permutation_grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
transcript.update_with_fr(proof.gate_selector_values_at_z[0]);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.copy_grand_product_at_z_omega);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function aggregate_for_verification(Proof memory proof, VerificationKey memory vk)
internal
view
returns (bool valid, PairingsBn254.G1Point[2] memory part)
{
PartialVerifierState memory state;
valid = verify_initial(state, proof, vk);
if (valid == false) {
return (valid, part);
}
part = aggregate_commitments(state, proof, vk);
(valid, part);
}
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
valid = PairingsBn254.pairingProd2(
recursive_proof_part[0],
PairingsBn254.P2(),
recursive_proof_part[1],
vk.g2_x
);
return valid;
}
function verify_recursive(
Proof memory proof,
VerificationKey memory vk,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs
) internal view returns (bool) {
(uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) =
reconstruct_recursive_public_input(
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
assert(recursive_input == proof.input_values[0]);
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
// aggregated_g1s = inner
// recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part);
valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x);
return valid;
}
function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer)
internal
view
returns (PairingsBn254.G1Point[2] memory result)
{
// reuse the transcript primitive
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
transcript.update_with_g1(inner[0]);
transcript.update_with_g1(inner[1]);
transcript.update_with_g1(outer[0]);
transcript.update_with_g1(outer[1]);
PairingsBn254.Fr memory challenge = transcript.get_challenge();
// 1 * inner + challenge * outer
result[0] = PairingsBn254.copy_g1(inner[0]);
result[1] = PairingsBn254.copy_g1(inner[1]);
PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge);
result[0].point_add_assign(tmp);
tmp = outer[1].point_mul(challenge);
result[1].point_add_assign(tmp);
return result;
}
function reconstruct_recursive_public_input(
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_aggregated
) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) {
assert(recursive_vks_indexes.length == individual_vks_inputs.length);
bytes memory concatenated = abi.encodePacked(recursive_vks_root);
uint8 index;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
index = recursive_vks_indexes[i];
assert(index <= max_valid_index);
concatenated = abi.encodePacked(concatenated, index);
}
uint256 input;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
input = individual_vks_inputs[i];
assert(input < r_mod);
concatenated = abi.encodePacked(concatenated, input);
}
concatenated = abi.encodePacked(concatenated, subproofs_aggregated);
bytes32 commitment = sha256(concatenated);
recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK;
reconstructed_g1s[0] = PairingsBn254.new_g1_checked(
subproofs_aggregated[0] +
(subproofs_aggregated[1] << LIMB_WIDTH) +
(subproofs_aggregated[2] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[3] << (3 * LIMB_WIDTH)),
subproofs_aggregated[4] +
(subproofs_aggregated[5] << LIMB_WIDTH) +
(subproofs_aggregated[6] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[7] << (3 * LIMB_WIDTH))
);
reconstructed_g1s[1] = PairingsBn254.new_g1_checked(
subproofs_aggregated[8] +
(subproofs_aggregated[9] << LIMB_WIDTH) +
(subproofs_aggregated[10] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[11] << (3 * LIMB_WIDTH)),
subproofs_aggregated[12] +
(subproofs_aggregated[13] << LIMB_WIDTH) +
(subproofs_aggregated[14] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[15] << (3 * LIMB_WIDTH))
);
return (recursive_input, reconstructed_g1s);
}
}
contract VerifierWithDeserialize is Plonk4VerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 34;
function deserialize_proof(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (Proof memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
function verify_serialized_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify(proof, vk);
return valid;
}
function verify_serialized_proof_with_recursion(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid =
verify_recursive(
proof,
vk,
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
return valid;
}
}
contract Plonk4VerifierWithAccessToDNextOld {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH_OLD = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD = 1;
struct VerificationKeyOld {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH_OLD + 2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH_OLD] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct ProofOld {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH_OLD] wire_commitments;
PairingsBn254.G1Point grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH_OLD] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] wire_values_at_z_omega;
PairingsBn254.Fr grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierStateOld {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain_old(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain_old(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length ; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(partial_products[i-1]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
tmp_1.assign(tmp_2); // all inversed
tmp_1.mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
dens[i].assign(tmp_1);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing_old(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing_old(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
rhs.add_assign(tmp);
}
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH_OLD - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function reconstruct_d(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^(6..8) * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^9 (z(x) - z(z*omega)) <- we need this power
// + v^10 * (d(x) - d(z*omega))
// ]
//
// we pay a little for a few arithmetic operations to not introduce another constant
uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH_OLD + STATE_WIDTH_OLD - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH_OLD + 1]);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.selector_commitments[STATE_WIDTH_OLD].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]);
res.point_add_assign(tmp_g1);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(state.alpha);
tmp_fr.mul_assign(state.alpha);
grand_product_part_at_z.add_assign(tmp_fr);
PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening);
grand_product_part_at_z_omega.mul_assign(state.u);
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(state.alpha);
// add to the linearization
tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH_OLD - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
res.point_mul_assign(state.v);
res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega));
}
function verify_commitments(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH_OLD - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x);
}
function verify_initial(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain_old(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
transcript.update_with_fr(proof.grand_product_at_z_omega);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function verify_old(ProofOld memory proof, VerificationKeyOld memory vk) internal view returns (bool) {
PartialVerifierStateOld memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract VerifierWithDeserializeOld is Plonk4VerifierWithAccessToDNextOld {
uint256 constant SERIALIZED_PROOF_LENGTH_OLD = 33;
function deserialize_proof_old(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (ProofOld memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH_OLD);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.grand_product_commitment = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
}
pragma solidity ^0.7.0;
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
contract UniswapV2Pair is UniswapV2ERC20 {
using UniswapSafeMath for uint;
using UQ112x112 for uint224;
address public factory;
address public token0;
address public token1;
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
constructor() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function mint(address to, uint256 amount) external lock {
require(msg.sender == factory, 'mt1');
_mint(to, amount);
}
function burn(address to, uint256 amount) external lock {
require(msg.sender == factory, 'br1');
_burn(to, amount);
}
}
pragma solidity ^0.7.0;
import './libraries/UniswapSafeMath.sol';
contract UniswapV2ERC20 {
using UniswapSafeMath for uint;
string public constant name = 'EdgeSwap V1';
string public constant symbol = 'Edge-V1';
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
pragma solidity ^0.7.0;
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity ^0.7.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity ^0.7.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library UniswapSafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable contract
/// @author Matter Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
} | uint8 opType; -- present in pubdata, ignored at serializationuint16 tokenId; -- present in pubdata, ignored at serializationuint16 fee; -- present in pubdata, ignored at serialization | struct ChangePubKey {
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
}
| 72,347 | [
1,
11890,
28,
1061,
559,
31,
1493,
3430,
316,
5634,
892,
16,
5455,
622,
11854,
11890,
2313,
1147,
548,
31,
1493,
3430,
316,
5634,
892,
16,
5455,
622,
11854,
11890,
2313,
14036,
31,
1493,
3430,
316,
5634,
892,
16,
5455,
622,
11854,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
7576,
17924,
288,
203,
3639,
2254,
1578,
17398,
31,
203,
3639,
1731,
3462,
18659,
2310,
31,
203,
3639,
1758,
3410,
31,
203,
3639,
2254,
1578,
7448,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol
pragma solidity ^0.5.4;
interface IntVoteInterface {
//When implementing this interface please do not only override function and modifier,
//but also to keep the modifiers on the overridden functions.
modifier ONLYPROPOSALOWNER208(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
modifier VOTABLE853(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
event NEWPROPOSAL588( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event EXECUTEPROPOSAL706(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VOTEPROPOSAL760( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CANCELPROPOSAL161(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING
event CANCELVOTING574(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING
function PROPOSE661( //inject NONSTANDARD NAMING
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function VOTE536( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function CANCELVOTE202(bytes32 _proposalId) external; //inject NONSTANDARD NAMING
function GETNUMBEROFCHOICES589(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function ISVOTABLE375(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING
function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING
function ISABSTAINALLOW791() external pure returns(bool); //inject NONSTANDARD NAMING
function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
interface IERC20 {
function TRANSFER985(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE946(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM649(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY573() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF995(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE88(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER258(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL578(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol
pragma solidity ^0.5.4;
interface VotingMachineCallbacksInterface {
function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function BURNREPUTATION898(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function STAKINGTOKENTRANSFER53(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
returns(bool);
function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED48(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED48(address(0), _owner);
}
function OWNER574() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER824() { //inject NONSTANDARD NAMING
require(ISOWNER625());
_;
}
function ISOWNER625() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP632() public ONLYOWNER824 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED48(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP334(address newOwner) public ONLYOWNER824 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP900(newOwner);
}
function _TRANSFEROWNERSHIP900(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED48(_owner, newOwner);
_owner = newOwner;
}
}
// File: @daostack/infra/contracts/Reputation.sol
pragma solidity ^0.5.4;
contract Reputation is Ownable {
uint8 public decimals = 18; //Number of decimals of the smallest unit
// Event indicating minting of reputation to an address.
event MINT335(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING
// Event indicating burning of reputation for an address.
event BURN261(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of reputation at a specific block number
uint128 value;
}
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the reputation
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING
return TOTALSUPPLYAT652(block.number);
}
// Query balance and totalSupply in History
function BALANCEOF995(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
return BALANCEOFAT780(_owner, block.number);
}
function BALANCEOFAT780(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected balance during normal situations
} else {
return GETVALUEAT483(balances[_owner], _blockNumber);
}
}
function TOTALSUPPLYAT652(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return GETVALUEAT483(totalSupplyHistory, _blockNumber);
}
}
function MINT69(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY573();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = BALANCEOF995(_user);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply + _amount);
UPDATEVALUEATNOW719(balances[_user], previousBalanceTo + _amount);
emit MINT335(_user, _amount);
return true;
}
function BURN206(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY573();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = BALANCEOF995(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply - amountBurned);
UPDATEVALUEATNOW719(balances[_user], previousBalanceFrom - amountBurned);
emit BURN261(_user, amountBurned);
return true;
}
// Internal helper functions to query and set a value in a snapshot array
function GETVALUEAT483(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING
if (checkpoints.length == 0) {
return 0;
}
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function UPDATEVALUEATNOW719(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
library SafeMath {
function MUL295(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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV1(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB141(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD15(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD36(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF995(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE88(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER985(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER402(msg.sender, to, value);
return true;
}
function APPROVE946(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE913(msg.sender, spender, value);
return true;
}
function TRANSFERFROM649(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER402(from, to, value);
_APPROVE913(from, msg.sender, _allowed[from][msg.sender].SUB141(value));
return true;
}
function INCREASEALLOWANCE616(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].ADD15(addedValue));
return true;
}
function DECREASEALLOWANCE72(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].SUB141(subtractedValue));
return true;
}
function _TRANSFER402(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB141(value);
_balances[to] = _balances[to].ADD15(value);
emit TRANSFER258(from, to, value);
}
function _MINT318(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD15(value);
_balances[account] = _balances[account].ADD15(value);
emit TRANSFER258(address(0), account, value);
}
function _BURN875(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB141(value);
_balances[account] = _balances[account].SUB141(value);
emit TRANSFER258(account, address(0), value);
}
function _APPROVE913(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit APPROVAL578(owner, spender, value);
}
function _BURNFROM507(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_BURN875(account, value);
_APPROVE913(account, msg.sender, _allowed[account][msg.sender].SUB141(value));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.2;
contract ERC20Burnable is ERC20 {
function BURN206(uint256 value) public { //inject NONSTANDARD NAMING
_BURN875(msg.sender, value);
}
function BURNFROM991(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM507(from, value);
}
}
// File: contracts/controller/DAOToken.sol
pragma solidity ^0.5.4;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals662 = 18; //inject NONSTANDARD NAMING
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function MINT69(address _to, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING
if (cap > 0)
require(TOTALSUPPLY573().ADD15(_amount) <= cap);
_MINT318(_to, _amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.2;
library Address {
function ISCONTRACT51(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
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.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: contracts/libs/SafeERC20.sol
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private transfer_selector475 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private transferfrom_selector4 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private approve_selector816 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING
function SAFETRANSFER442(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT51());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transfer_selector475, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFETRANSFERFROM294(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT51());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transferfrom_selector4, _from, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFEAPPROVE771(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT51());
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero.
require((_value == 0) || (IERC20(_erc20Addr).ALLOWANCE88(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(approve_selector816, _spender, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
// File: contracts/controller/Avatar.sol
pragma solidity ^0.5.4;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GENERICCALL988(address indexed _contract, bytes _data, uint _value, bool _success); //inject NONSTANDARD NAMING
event SENDETHER194(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFER653(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFERFROM913(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENAPPROVAL142(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING
event RECEIVEETHER18(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING
event METADATA150(string _metaData); //inject NONSTANDARD NAMING
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit RECEIVEETHER18(msg.sender, msg.value);
}
function GENERICCALL327(address _contract, bytes memory _data, uint256 _value) //inject NONSTANDARD NAMING
public
ONLYOWNER824
returns(bool success, bytes memory returnValue) {
// solhint-disable-next-line avoid-call-value
(success, returnValue) = _contract.call.value(_value)(_data);
emit GENERICCALL988(_contract, _data, _value, success);
}
function SENDETHER177(uint256 _amountInWei, address payable _to) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING
_to.transfer(_amountInWei);
emit SENDETHER194(_amountInWei, _to);
return true;
}
function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER824 returns(bool)
{
address(_externalToken).SAFETRANSFER442(_to, _value);
emit EXTERNALTOKENTRANSFER653(address(_externalToken), _to, _value);
return true;
}
function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public ONLYOWNER824 returns(bool)
{
address(_externalToken).SAFETRANSFERFROM294(_from, _to, _value);
emit EXTERNALTOKENTRANSFERFROM913(address(_externalToken), _from, _to, _value);
return true;
}
function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER824 returns(bool)
{
address(_externalToken).SAFEAPPROVE771(_spender, _value);
emit EXTERNALTOKENAPPROVAL142(address(_externalToken), _spender, _value);
return true;
}
function METADATA450(string memory _metaData) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING
emit METADATA150(_metaData);
return true;
}
}
// File: contracts/universalSchemes/UniversalSchemeInterface.sol
pragma solidity ^0.5.4;
contract UniversalSchemeInterface {
function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING
}
// File: contracts/globalConstraints/GlobalConstraintInterface.sol
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function PRE222( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function POST74( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function WHEN422() public returns(CallPhase); //inject NONSTANDARD NAMING
}
// File: contracts/controller/ControllerInterface.sol
pragma solidity ^0.5.4;
interface ControllerInterface {
function MINTREPUTATION981(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function BURNREPUTATION898(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function MINTTOKENS758(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function REGISTERSCHEME37(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSCHEME785(address _scheme, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSELF96(address _avatar) external returns(bool); //inject NONSTANDARD NAMING
function ADDGLOBALCONSTRAINT638(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function REMOVEGLOBALCONSTRAINT28 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function UPGRADECONTROLLER721(address _newController, Avatar _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function GENERICCALL327(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value) //inject NONSTANDARD NAMING
external
returns(bool, bytes memory);
function SENDETHER177(uint256 _amountInWei, address payable _to, Avatar _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function METADATA450(string calldata _metaData, Avatar _avatar) external returns(bool); //inject NONSTANDARD NAMING
function GETNATIVEREPUTATION762(address _avatar) //inject NONSTANDARD NAMING
external
view
returns(address);
function ISSCHEMEREGISTERED658( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
function GETSCHEMEPARAMETERS578(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETGLOBALCONSTRAINTPARAMETERS702(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETSCHEMEPERMISSIONS800(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING
function GLOBALCONSTRAINTSCOUNT83(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING
function ISGLOBALCONSTRAINTREGISTERED605(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
}
// File: contracts/universalSchemes/UniversalScheme.sol
pragma solidity ^0.5.4;
contract UniversalScheme is UniversalSchemeInterface {
function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING
require(ControllerInterface(_avatar.OWNER574()).ISSCHEMEREGISTERED658(address(this), address(_avatar)),
"scheme is not registered");
return ControllerInterface(_avatar.OWNER574()).GETSCHEMEPARAMETERS578(address(this), address(_avatar));
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
pragma solidity ^0.5.2;
library ECDSA {
function RECOVER336(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING
// 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 1 2 + 1, and for v in (282): v 1 {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);
}
function TOETHSIGNEDMESSAGEHASH747(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: @daostack/infra/contracts/libs/RealMath.sol
pragma solidity ^0.5.4;
library RealMath {
uint256 constant private real_bits978 = 256; //inject NONSTANDARD NAMING
uint256 constant private real_fbits102 = 40; //inject NONSTANDARD NAMING
uint256 constant private real_one722 = uint256(1) << real_fbits102; //inject NONSTANDARD NAMING
function POW948(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
// Start with the 0th power
uint256 realResult = real_one722;
while (tempExponent != 0) {
// While there are still bits set
if ((tempExponent & 0x1) == 0x1) {
// If the low bit is set, multiply in the (many-times-squared) base
realResult = MUL295(realResult, tempRealBase);
}
// Shift off the low bit
tempExponent = tempExponent >> 1;
if (tempExponent != 0) {
// Do the squaring
tempRealBase = MUL295(tempRealBase, tempRealBase);
}
}
// Return the final result.
return realResult;
}
function FRACTION401(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV1(uint256(numerator) * real_one722, uint256(denominator) * real_one722);
}
function MUL295(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
uint256 res = realA * realB;
require(res/realA == realB, "RealMath mul overflow");
return (res >> real_fbits102);
}
function DIV1(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return uint256((uint256(realNumerator) * real_one722) / uint256(realDenominator));
}
}
// File: @daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol
pragma solidity ^0.5.4;
interface ProposalExecuteInterface {
function EXECUTEPROPOSAL422(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.5.2;
library Math {
function MAX135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN317(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE86(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol
pragma solidity ^0.5.4;
contract GenesisProtocolLogic is IntVoteInterface {
using SafeMath for uint256;
using Math for uint256;
using RealMath for uint216;
using RealMath for uint256;
using Address for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
//Organization's parameters
struct Parameters {
uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar.
uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode.
uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode.
uint256 preBoostedVotePeriodLimit; //the time limit for a proposal
//to be in an preparation state (stable) before boosted.
uint256 thresholdConst; //constant for threshold calculation .
//threshold =thresholdConst ** (numberOfBoostedProposals)
uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals
//in the threshold calculation to prevent overflow
uint256 quietEndingPeriod; //quite ending period
uint256 proposingRepReward;//proposer reputation reward.
uint256 votersReputationLossRatio;//Unsuccessful pre booster
//voters lose votersReputationLossRatio% of their reputation.
uint256 minimumDaoBounty;
uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula
//(daoBountyConst * averageBoostDownstakes)/100 .
uint256 activationTime;//the point in time after which proposals can be created.
//if this address is set so only this address is allowed to vote of behalf of someone else.
address voteOnBehalf;
}
struct Voter {
uint256 vote; // YES(1) ,NO(2)
uint256 reputation; // amount of voter's reputation
bool preBoosted;
}
struct Staker {
uint256 vote; // YES(1) ,NO(2)
uint256 amount; // amount of staker's stake
uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation.
}
struct Proposal {
bytes32 organizationId; // the organization unique identifier the proposal is target to.
address callbacks; // should fulfill voting callbacks interface.
ProposalState state;
uint256 winningVote; //the winning vote.
address proposer;
//the proposal boosted period limit . it is updated for the case of quiteWindow mode.
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time.
uint256 daoBounty;
uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers.
uint256 confidenceThreshold;
//The percentage from upper stakes which the caller for the expiration was given.
uint256 expirationCallBountyPercentage;
uint[3] times; //times[0] - submittedTime
//times[1] - boostedPhaseTime
//times[2] -preBoostedPhaseTime;
bool daoRedeemItsWinnings;
// vote reputation
mapping(uint256 => uint256 ) votes;
// vote reputation
mapping(uint256 => uint256 ) preBoostedVotes;
// address voter
mapping(address => Voter ) voters;
// vote stakes
mapping(uint256 => uint256 ) stakes;
// address staker
mapping(address => Staker ) stakers;
}
event STAKE754(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event REDEEM636(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMDAOBOUNTY578(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMREPUTATION314(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event STATECHANGE374(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING
event GPEXECUTEPROPOSAL538(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING
event EXPIRATIONCALLBOUNTY93(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING
event CONFIDENCELEVELCHANGE532(bytes32 indexed _proposalId, uint256 _confidenceThreshold); //inject NONSTANDARD NAMING
mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters
mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself.
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
//organizationId => organization
mapping(bytes32 => address ) public organizations;
//organizationId => averageBoostDownstakes
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public num_of_choices613 = 2; //inject NONSTANDARD NAMING
uint256 constant public no391 = 2; //inject NONSTANDARD NAMING
uint256 constant public yes596 = 1; //inject NONSTANDARD NAMING
uint256 public proposalsCnt; // Total number of proposals
IERC20 public stakingToken;
address constant private gen_token_address929 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING
uint256 constant private max_boosted_proposals645 = 4096; //inject NONSTANDARD NAMING
constructor(IERC20 _stakingToken) public {
//The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS .
//This will work for a network which already hosted the GEN token on this address (e.g mainnet).
//If such contract address does not exist in the network (e.g ganache)
//the contract will use the _stakingToken param as the
//staking token address.
if (address(gen_token_address929).ISCONTRACT51()) {
stakingToken = IERC20(gen_token_address929);
} else {
stakingToken = _stakingToken;
}
}
modifier VOTABLE853(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(_ISVOTABLE722(_proposalId));
_;
}
function PROPOSE661(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING
external
returns(bytes32)
{
// solhint-disable-next-line not-rely-on-time
require(now > parameters[_paramsHash].activationTime, "not active yet");
//Check parameters existence.
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
// Generate a unique ID:
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.ADD15(1);
// Open proposal:
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
// solhint-disable-next-line not-rely-on-time
proposal.times[0] = now;//submitted time
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = no391;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
//calc dao bounty
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.MUL295(averagesDownstakesOfBoosted[proposal.organizationId]).DIV1(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[no391] = proposal.daoBountyRemain;//dao downstake on the proposal
emit NEWPROPOSAL588(proposalId, organizations[proposal.organizationId], num_of_choices613, _proposer, _paramsHash);
return proposalId;
}
function EXECUTEBOOSTED17(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
"proposal state in not Boosted nor QuietEndingPeriod");
require(_EXECUTE501(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
// solhint-disable-next-line not-rely-on-time
(uint(1).ADD15(now.SUB141(proposal.currentBoostedVotePeriodLimit.ADD15(proposal.times[1])).DIV1(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100);
require(stakingToken.TRANSFER985(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit EXPIRATIONCALLBOUNTY93(_proposalId, msg.sender, expirationCallBounty);
}
function SETPARAMETERS600( //inject NONSTANDARD NAMING
uint[11] calldata _params, //use array here due to stack too deep issue.
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = GETPARAMETERSHASH529(_params, _voteOnBehalf);
//set a limit for power for a given alpha to prevent overflow
uint256 limitExponent = 172;//for alpha less or equal 2
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).FRACTION401(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
// solhint-disable-next-line function-max-lines,code-complexity
function REDEEM641(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == yes596) {
lostReputation = proposal.preBoostedVotes[no391];
} else {
lostReputation = proposal.preBoostedVotes[yes596];
}
lostReputation = (lostReputation.MUL295(params.votersReputationLossRatio))/100;
//as staker
Staker storage staker = proposal.stakers[_beneficiary];
uint256 totalStakes = proposal.stakes[no391].ADD15(proposal.stakes[yes596]);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
if (staker.amount > 0) {
uint256 totalStakesLeftAfterCallBounty =
totalStakes.SUB141(proposal.expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100));
if (proposal.state == ProposalState.ExpiredInQueue) {
//Stakes of a proposal that expires in Queue are sent back to stakers
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
if (staker.vote == yes596) {
if (proposal.daoBounty < totalStakesLeftAfterCallBounty) {
uint256 _totalStakes = totalStakesLeftAfterCallBounty.SUB141(proposal.daoBounty);
rewards[0] = (staker.amount.MUL295(_totalStakes))/totalWinningStakes;
}
} else {
rewards[0] = (staker.amount.MUL295(totalStakesLeftAfterCallBounty))/totalWinningStakes;
}
}
staker.amount = 0;
}
//dao redeem its winnings
if (proposal.daoRedeemItsWinnings == false &&
_beneficiary == organizations[proposal.organizationId] &&
proposal.state != ProposalState.ExpiredInQueue &&
proposal.winningVote == no391) {
rewards[0] =
rewards[0].ADD15((proposal.daoBounty.MUL295(totalStakes))/totalWinningStakes).SUB141(proposal.daoBounty);
proposal.daoRedeemItsWinnings = true;
}
//as voter
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
//give back reputation for the voter
rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100)
.ADD15((voter.reputation.MUL295(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]);
}
voter.reputation = 0;
}
//as proposer
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes596)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.SUB141(rewards[0]);
require(stakingToken.TRANSFER985(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit REDEEM636(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].ADD15(rewards[2]) != 0) {
VotingMachineCallbacksInterface(proposal.callbacks)
.MINTREPUTATION981(rewards[1].ADD15(rewards[2]), _beneficiary, _proposalId);
emit REDEEMREPUTATION314(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].ADD15(rewards[2])
);
}
}
function REDEEMDAOBOUNTY8(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == yes596)&&
(totalWinningStakes != 0)) {
//as staker
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(VotingMachineCallbacksInterface(proposal.callbacks)
.BALANCEOFSTAKINGTOKEN878(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.SUB141(potentialAmount);
require(
VotingMachineCallbacksInterface(proposal.callbacks)
.STAKINGTOKENTRANSFER53(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit REDEEMDAOBOUNTY578(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function SHOULDBOOST603(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING
Proposal memory proposal = proposals[_proposalId];
return (_SCORE635(_proposalId) > THRESHOLD53(proposal.paramsHash, proposal.organizationId));
}
function THRESHOLD53(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.POW948(power);
}
function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING
uint[11] memory _params,//use array here due to stack too deep issue.
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
//double call to keccak256 to avoid deep stack issue when call with too many params.
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
// solhint-disable-next-line function-max-lines,code-complexity
function _EXECUTE501(bytes32 _proposalId) internal VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
VotingMachineCallbacksInterface(proposal.callbacks).GETTOTALREPUTATIONSUPPLY50(_proposalId);
//first divide by 100 to prevent overflow
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = no391;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId);
if (_SCORE635(_proposalId) > confidenceThreshold) {
//change proposal mode to PreBoosted mode.
proposal.state = ProposalState.PreBoosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId);
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_SCORE635(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals645)) {
//change proposal mode to Boosted mode.
proposal.state = ProposalState.Boosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
//add a value to average -> average = average + ((value - average) / nbValues)
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
// solium-disable-next-line indentation
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[no391])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else { //check the Confidence level is stable
uint256 proposalScore = _SCORE635(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.MIN317(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
emit CONFIDENCELEVELCHANGE532(_proposalId, confidenceThreshold);
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].SUB141(1);
//remove a value from average = ((average * nbValues) - value) / (nbValues - 1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.MUL295(boostedProposals+1).SUB141(proposal.stakes[no391]))/boostedProposals;
}
}
emit EXECUTEPROPOSAL706(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPEXECUTEPROPOSAL538(_proposalId, executionState);
ProposalExecuteInterface(proposal.callbacks).EXECUTEPROPOSAL422(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit STATECHANGE374(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _STAKE234(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING
// 0 is not a valid vote.
require(_vote <= num_of_choices613 && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_EXECUTE501(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
// enable to increase stake only on the previous stake vote
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.TRANSFERFROM649(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.ADD15(amount); //update totalRedeemableStakes
staker.amount = staker.amount.ADD15(amount);
//This is to prevent average downstakes calculation overflow
//Note that any how GEN cap is 100000000 ether.
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == yes596) {
staker.amount4Bounty = staker.amount4Bounty.ADD15(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.ADD15(proposal.stakes[_vote]);
emit STAKE754(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _EXECUTE501(_proposalId);
}
// solhint-disable-next-line function-max-lines,code-complexity
function INTERNALVOTE757(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING
require(_vote <= num_of_choices613 && _vote > 0, "0 < _vote <= 2");
if (_EXECUTE501(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
// Check voter has enough reputation:
uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).REPUTATIONOF984(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
// If this voter has already voted, return false.
if (proposal.voters[_voter].reputation != 0) {
return false;
}
// The voting itself:
proposal.votes[_vote] = rep.ADD15(proposal.votes[_vote]);
//check if the current winningVote changed or there is a tie.
//for the case there is a tie the current winningVote set to NO.
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[no391] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == yes596)) {
if (proposal.state == ProposalState.Boosted &&
// solhint-disable-next-line not-rely-on-time
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
//quietEndingPeriod
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.ADD15(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.MUL295(rep))/100;
VotingMachineCallbacksInterface(proposal.callbacks).BURNREPUTATION898(reputationDeposit, _voter, _proposalId);
}
emit VOTEPROPOSAL760(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _EXECUTE501(_proposalId);
}
function _SCORE635(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
//proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal.
return uint216(proposal.stakes[yes596]).FRACTION401(uint216(proposal.stakes[no391]));
}
function _ISVOTABLE722(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
// File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol
pragma solidity ^0.5.4;
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic {
using ECDSA for bytes32;
// Digest describing the data the user signs according EIP 712.
// Needs to match what is passed to Metamask.
bytes32 public constant delegation_hash_eip712291 = //inject NONSTANDARD NAMING
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce; //stakes Nonce
constructor(IERC20 _stakingToken)
public
// solhint-disable-next-line no-empty-blocks
GenesisProtocolLogic(_stakingToken) {
}
function STAKE53(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING
return _STAKE234(_proposalId, _vote, _amount, msg.sender);
}
function STAKEWITHSIGNATURE42( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
// Recreate the digest the user signed
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
delegation_hash_eip712291, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).TOETHSIGNEDMESSAGEHASH747();
}
address staker = delegationDigest.RECOVER336(_signature);
//a garbage staker address due to wrong signature will revert due to lack of approval and funds.
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].ADD15(1);
return _STAKE234(_proposalId, _vote, _amount, staker);
}
function VOTE536(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING
external
VOTABLE853(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return INTERNALVOTE757(_proposalId, voter, _vote, _amount);
}
function CANCELVOTE202(bytes32 _proposalId) external VOTABLE853(_proposalId) { //inject NONSTANDARD NAMING
//this is not allowed
return;
}
function EXECUTE916(bytes32 _proposalId) external VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
return _EXECUTE501(_proposalId);
}
function GETNUMBEROFCHOICES589(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING
return num_of_choices613;
}
function GETPROPOSALTIMES314(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING
return proposals[_proposalId].times;
}
function VOTEINFO167(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].votes[_choice];
}
function ISVOTABLE375(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING
return _ISVOTABLE722(_proposalId);
}
function PROPOSALSTATUS186(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING
return (
proposals[_proposalId].preBoostedVotes[yes596],
proposals[_proposalId].preBoostedVotes[no391],
proposals[_proposalId].stakes[yes596],
proposals[_proposalId].stakes[no391]
);
}
function GETPROPOSALORGANIZATION49(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].organizationId);
}
function GETSTAKER814(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function VOTESTAKE56(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].stakes[_vote];
}
function WINNINGVOTE889(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].winningVote;
}
function STATE293(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING
return proposals[_proposalId].state;
}
function ISABSTAINALLOW791() external pure returns(bool) { //inject NONSTANDARD NAMING
return false;
}
function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING
return (yes596, no391);
}
function SCORE81(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING
return _SCORE635(_proposalId);
}
}
// File: contracts/votingMachines/VotingMachineCallbacks.sol
pragma solidity ^0.5.4;
contract VotingMachineCallbacks is VotingMachineCallbacksInterface {
struct ProposalInfo {
uint256 blockNumber; // the proposal's block number
Avatar avatar; // the proposal's avatar
}
modifier ONLYVOTINGMACHINE284(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine");
_;
}
// VotingMaching -> proposalId -> ProposalInfo
mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo;
function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE284(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.OWNER574()).MINTREPUTATION981(_amount, _beneficiary, address(avatar));
}
function BURNREPUTATION898(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE284(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.OWNER574()).BURNREPUTATION898(_amount, _beneficiary, address(avatar));
}
function STAKINGTOKENTRANSFER53( //inject NONSTANDARD NAMING
IERC20 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
ONLYVOTINGMACHINE284(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.OWNER574()).EXTERNALTOKENTRANSFER167(_stakingToken, _beneficiary, _amount, avatar);
}
function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) {
return 0;
}
return _stakingToken.BALANCEOF995(address(avatar));
}
function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().TOTALSUPPLYAT652(proposal.blockNumber);
}
function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().BALANCEOFAT780(_owner, proposal.blockNumber);
}
}
// File: contracts/universalSchemes/SchemeRegistrar.sol
pragma solidity ^0.5.4;
contract SchemeRegistrar is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface {
event NEWSCHEMEPROPOSAL971( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
address _scheme,
bytes32 _parametersHash,
bytes4 _permissions,
string _descriptionHash
);
event REMOVESCHEMEPROPOSAL965(address indexed _avatar, //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
address _scheme,
string _descriptionHash
);
event PROPOSALEXECUTED934(address indexed _avatar, bytes32 indexed _proposalId, int256 _param); //inject NONSTANDARD NAMING
event PROPOSALDELETED307(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING
// a SchemeProposal is a proposal to add or remove a scheme to/from the an organization
struct SchemeProposal {
address scheme; //
bool addScheme; // true: add a scheme, false: remove a scheme.
bytes32 parametersHash;
bytes4 permissions;
}
// A mapping from the organization (Avatar) address to the saved data of the organization:
mapping(address=>mapping(bytes32=>SchemeProposal)) public organizationsProposals;
// A mapping from hashes to parameters (use to store a particular configuration on the controller)
struct Parameters {
bytes32 voteRegisterParams;
bytes32 voteRemoveParams;
IntVoteInterface intVote;
}
mapping(bytes32=>Parameters) public parameters;
function EXECUTEPROPOSAL422(bytes32 _proposalId, int256 _param) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.scheme != address(0));
delete organizationsProposals[address(avatar)][_proposalId];
emit PROPOSALDELETED307(address(avatar), _proposalId);
if (_param == 1) {
// Define controller and get the params:
ControllerInterface controller = ControllerInterface(avatar.OWNER574());
// Add a scheme:
if (proposal.addScheme) {
require(controller.REGISTERSCHEME37(
proposal.scheme,
proposal.parametersHash,
proposal.permissions,
address(avatar))
);
}
// Remove a scheme:
if (!proposal.addScheme) {
require(controller.UNREGISTERSCHEME785(proposal.scheme, address(avatar)));
}
}
emit PROPOSALEXECUTED934(address(avatar), _proposalId, _param);
return true;
}
function SETPARAMETERS600( //inject NONSTANDARD NAMING
bytes32 _voteRegisterParams,
bytes32 _voteRemoveParams,
IntVoteInterface _intVote
) public returns(bytes32)
{
bytes32 paramsHash = GETPARAMETERSHASH529(_voteRegisterParams, _voteRemoveParams, _intVote);
parameters[paramsHash].voteRegisterParams = _voteRegisterParams;
parameters[paramsHash].voteRemoveParams = _voteRemoveParams;
parameters[paramsHash].intVote = _intVote;
return paramsHash;
}
function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING
bytes32 _voteRegisterParams,
bytes32 _voteRemoveParams,
IntVoteInterface _intVote
) public pure returns(bytes32)
{
return keccak256(abi.encodePacked(_voteRegisterParams, _voteRemoveParams, _intVote));
}
function PROPOSESCHEME503( //inject NONSTANDARD NAMING
Avatar _avatar,
address _scheme,
bytes32 _parametersHash,
bytes4 _permissions,
string memory _descriptionHash
)
public
returns(bytes32)
{
// propose
require(_scheme != address(0), "scheme cannot be zero");
Parameters memory controllerParams = parameters[GETPARAMETERSFROMCONTROLLER560(_avatar)];
bytes32 proposalId = controllerParams.intVote.PROPOSE661(
2,
controllerParams.voteRegisterParams,
msg.sender,
address(_avatar)
);
SchemeProposal memory proposal = SchemeProposal({
scheme: _scheme,
parametersHash: _parametersHash,
addScheme: true,
permissions: _permissions
});
emit NEWSCHEMEPROPOSAL971(
address(_avatar),
proposalId,
address(controllerParams.intVote),
_scheme, _parametersHash,
_permissions,
_descriptionHash
);
organizationsProposals[address(_avatar)][proposalId] = proposal;
proposalsInfo[address(controllerParams.intVote)][proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
return proposalId;
}
function PROPOSETOREMOVESCHEME279(Avatar _avatar, address _scheme, string memory _descriptionHash) //inject NONSTANDARD NAMING
public
returns(bytes32)
{
require(_scheme != address(0), "scheme cannot be zero");
bytes32 paramsHash = GETPARAMETERSFROMCONTROLLER560(_avatar);
Parameters memory params = parameters[paramsHash];
IntVoteInterface intVote = params.intVote;
bytes32 proposalId = intVote.PROPOSE661(2, params.voteRemoveParams, msg.sender, address(_avatar));
organizationsProposals[address(_avatar)][proposalId].scheme = _scheme;
emit REMOVESCHEMEPROPOSAL965(address(_avatar), proposalId, address(intVote), _scheme, _descriptionHash);
proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
return proposalId;
}
}
| inject NONSTANDARD NAMING
| function INTERNALVOTE757(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { | 15,855,861 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18139,
16169,
1448,
5877,
27,
12,
3890,
1578,
389,
685,
8016,
548,
16,
1758,
389,
90,
20005,
16,
2254,
5034,
389,
25911,
16,
2254,
5034,
389,
14462,
13,
2713,
1135,
12,
6430,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* @notice https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
library SafeMath {
/**
* SafeMath mul function
* @dev function for safe multiply
**/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/**
* SafeMath div funciotn
* @dev function for safe devide
**/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
/**
* SafeMath sub function
* @dev function for safe subtraction
**/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* SafeMath add fuction
* @dev function for safe addition
**/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simple version of ERC20 interface
* @notice https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title BasicToken
* @dev Basic version of Token, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* BasicToken transfer function
* @dev transfer token for a specified address
* @param _to address to transfer to.
* @param _value amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
//Safemath fnctions will throw if value is invalid
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* BasicToken balanceOf function
* @dev Gets the balance of the specified address.
* @param _owner address to get balance of.
* @return uint256 amount owned by the address.
*/
function balanceOf(address _owner) public constant returns (uint256 bal) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @notice https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Token
* @dev Token to meet the ERC20 standard
* @notice https://github.com/ethereum/EIPs/issues/20
*/
contract Token is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* Token transferFrom function
* @dev Transfer tokens from one address to another
* @param _from address to send tokens from
* @param _to address to transfer to
* @param _value amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
// Safe math functions will throw if value invalid
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* Token approve function
* @dev Aprove address to spend amount of tokens
* @param _spender address to spend the funds.
* @param _value amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// @notice https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
assert((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Token allowance method
* @dev Ckeck that owners tokens is allowed to send to spender
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Lavevel Token
* @dev Simple ERC20 Token with standard token functions.
*/
contract LavevelToken is Token {
string public constant NAME = "Googlier Token";
string public constant SYMBOL = "GOOGLIER";
uint256 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 500000000 * 10**18;
/**
* Kimera Token Constructor
* @dev Create and issue tokens to msg.sender.
*/
function LavevelToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
/**
* @title Ownable
* @dev Ownable has an owner address to simplify "user permissions".
*/
contract Ownable {
address public owner;
/**
* Ownable
* @dev Ownable constructor sets the `owner` of the contract to sender
*/
function Ownable() public {
owner = msg.sender;
}
/**
* ownerOnly
* @dev Throws an error if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* transferOwnership
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title Token
* @dev API interface for interacting with the WILD Token contract
*/
/**
* @title LavevelICO
* @dev LavevelICO contract is Ownable
**/
contract LavevelICO is Ownable {
using SafeMath for uint256;
Token token;
uint256 public constant RATE = 3000; // Number of tokens per Ether
uint256 public constant CAP = 5350; // Cap in Ether
uint256 public constant START = 1519862400; // Mar 26, 2018 @ 12:00 EST
uint256 public constant DAYS = 45; // 45 Day
uint256 public constant initialTokens = 6000000 * 10**18; // Initial number of tokens available
bool public initialized = false;
uint256 public raisedAmount = 0;
/**
* BoughtTokens
* @dev Log tokens bought onto the blockchain
*/
event BoughtTokens(address indexed to, uint256 value);
/**
* whenSaleIsActive
* @dev ensures that the contract is still active
**/
modifier whenSaleIsActive() {
// Check if sale is active
assert(isActive());
_;
}
/**
* LavevelICO
* @dev LavevelICO constructor
**/
function LavevelICO(address _tokenAddr) public {
require(_tokenAddr != 0);
token = Token(_tokenAddr);
}
/**
* initialize
* @dev Initialize the contract
**/
function initialize() public onlyOwner {
require(initialized == true); // Can only be initialized once
require(tokensAvailable() == initialTokens); // Must have enough tokens allocated
initialized = true;
}
/**
* isActive
* @dev Determins if the contract is still active
**/
function isActive() public view returns (bool) {
return (
initialized == true &&
now >= START && // Must be after the START date
now <= START.add(DAYS * 1 days) && // Must be before the end date
goalReached() == false // Goal must not already be reached
);
}
/**
* goalReached
* @dev Function to determin is goal has been reached
**/
function goalReached() public view returns (bool) {
return (raisedAmount >= CAP * 1 ether);
}
/**
* @dev Fallback function if ether is sent to address insted of buyTokens function
**/
function () public payable {
buyTokens();
}
/**
* buyTokens
* @dev function that sells available tokens
**/
function buyTokens() public payable whenSaleIsActive {
uint256 weiAmount = msg.value; // Calculate tokens to sell
uint256 tokens = weiAmount.mul(RATE);
emit BoughtTokens(msg.sender, tokens); // log event onto the blockchain
raisedAmount = raisedAmount.add(msg.value); // Increment raised amount
token.transfer(msg.sender, tokens); // Send tokens to buyer
owner.transfer(msg.value);// Send money to owner
}
/**
* tokensAvailable
* @dev returns the number of tokens allocated to this contract
**/
function tokensAvailable() public constant returns (uint256) {
return token.balanceOf(this);
}
/**
* destroy
* @notice Terminate contract and refund to owner
**/
function destroy() onlyOwner public {
// Transfer tokens back to owner
uint256 balance = token.balanceOf(this);
assert(balance > 0);
token.transfer(owner, balance);
// There should be no ether in the contract but just in case
selfdestruct(owner);
}
} | * initialize @dev Initialize the contract/ | function initialize() public onlyOwner {
initialized = true;
}
| 1,824,630 | [
1,
11160,
225,
9190,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
4046,
1435,
1071,
1338,
5541,
288,
203,
1377,
6454,
273,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.2;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
// input /Users/GustavoIbarra/Projects/Solidity/blockchain-asset-registry/contracts/vRC20.sol
// flattened : Thursday, 11-Apr-19 23:33:19 UTC
interface IVersioned {
event AppendedData( string data, uint256 versionIndex );
/*
* @dev fallback function
*/
function() external;
/**
* @dev Appends data to a string[] list
* @param _data any string. Could be an IPFS hash
*/
function appendData(string calldata _data) external returns (bool);
/**
* @dev Gets the current index of the data list
*/
function getVersionIndex() external view returns (uint count);
}
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);
}
library SafeMath {
/**
* @dev Multiplies two unsigned integers, 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 unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 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 unsigned integers, 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 unsigned integers, 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 unsigned integers 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;
}
}
contract Ownable {
/**
* @dev The current owner of the contract
*/
address payable private _owner;
/**
* @dev A list of the contract owners
*/
address[] private _owners;
/**
* @dev The pending owner.
* The current owner must have transferred the contract to this address
* The pending owner must claim the ownership
*/
address payable private _pendingOwner;
/**
* @dev A list of addresses that are allowed to transfer
* the contract ownership on behalf of the current owner
*/
mapping (address => mapping (address => bool)) internal allowed;
event PendingTransfer( address indexed owner, address indexed pendingOwner );
event OwnershipTransferred( address indexed previousOwner, address indexed newOwner );
event Approval( address indexed owner, address indexed trustee );
event RemovedApproval( address indexed owner, address indexed trustee );
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner {
require(isPendingOwner());
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @dev The Asset constructor sets the original `owner`
* of the contract to the sender account.
*/
constructor() public {
_owner = msg.sender;
_owners.push(_owner);
emit OwnershipTransferred(address(0), _owner);
}
/*
* @dev fallback function
*/
function() external {}
/**
* @return the set asset owner
*/
function owner() public view returns (address payable) {
return _owner;
}
/**
* @return the set asset owner
*/
function owners() public view returns (address[] memory) {
return _owners;
}
/**
* @return the set asset pendingOwner
*/
function pendingOwner() public view returns (address) {
return _pendingOwner;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isPendingOwner() public view returns (bool) {
return msg.sender == _pendingOwner;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param pendingOwner_ The address to transfer ownership to.
*/
function transferOwnership(address payable pendingOwner_) onlyOwner public {
_pendingOwner = pendingOwner_;
emit PendingTransfer(_owner, _pendingOwner);
}
/**
* @dev Allows an approved trustee to set the pendingOwner address.
* @param pendingOwner_ The address to transfer ownership to.
*/
function transferOwnershipFrom(address payable pendingOwner_) public {
require(allowance(msg.sender));
_pendingOwner = pendingOwner_;
emit PendingTransfer(_owner, _pendingOwner);
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
_owner = _pendingOwner;
_owners.push(_owner);
_pendingOwner = address(0);
emit OwnershipTransferred(_owner, _pendingOwner);
}
/**
* @dev Approve the passed address to transfer the Asset on behalf of msg.sender.
* @param trustee The address which will spend the funds.
*/
function approve(address trustee) onlyOwner public returns (bool) {
allowed[msg.sender][trustee] = true;
emit Approval(msg.sender, trustee);
return true;
}
/**
* @dev Approve the passed address to transfer the Asset on behalf of msg.sender.
* @param trustee The address which will spend the funds.
*/
function removeApproval(address trustee) onlyOwner public returns (bool) {
allowed[msg.sender][trustee] = false;
emit RemovedApproval(msg.sender, trustee);
return true;
}
/**
* @dev Function to check if a trustee is allowed to transfer on behalf the owner
* @param trustee address The address which will spend the funds.
* @return A bool specifying if the trustee can still transfer the Asset
*/
function allowance(address trustee) public view returns (bool) {
return allowed[_owner][trustee];
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
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;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
contract Versioned is IVersioned {
string[] public data;
event AppendedData(
string data,
uint256 versionIndex
);
/*
* @dev fallback function
*/
function() external {}
/**
* @dev Add data to the _data array
* @param _data string data
*/
function appendData(string memory _data) public returns (bool) {
return _appendData(_data);
}
/**
* @dev Add data to the _data array
* @param _data string data
*/
function _appendData(string memory _data) internal returns (bool) {
data.push(_data);
emit AppendedData(_data, getVersionIndex());
return true;
}
/**
* @dev Gets the current index of the data list
*/
function getVersionIndex() public view returns (uint count) {
return data.length - 1;
}
}
contract vRC20 is ERC20, ERC20Detailed, Versioned, Ownable {
constructor (
uint256 supply,
string memory name,
string memory symbol,
uint8 decimals
) public ERC20Detailed (name, symbol, decimals) {
_mint(msg.sender, supply);
}
/**
* @dev Add data to the _data array
* @param _data string data
*/
function appendData(string memory _data) public onlyOwner returns (bool) {
return _appendData(_data);
}
} | * @dev Add data to the _data array @param _data string data/ | function _appendData(string memory _data) internal returns (bool) {
data.push(_data);
emit AppendedData(_data, getVersionIndex());
return true;
}
| 13,096,936 | [
1,
986,
501,
358,
326,
389,
892,
526,
225,
389,
892,
533,
501,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
6923,
751,
12,
1080,
3778,
389,
892,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
501,
18,
6206,
24899,
892,
1769,
203,
3639,
3626,
1716,
11275,
751,
24899,
892,
16,
8343,
1016,
10663,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/40/0x4b7CfCB288D811cF68d32d1abcE3c621ed69Dce0/sources/src/Libraries/LibFees.sol | Rubic fixed fee for swap | struct FeesStorage {
mapping(address => IFeesFacet.IntegratorFeeInfo) integratorToFeeInfo;
uint256 RubicPlatformFee;
uint256 fixedNativeFee;
address feeTreasure;
bool initialized;
}
| 9,541,977 | [
1,
54,
17616,
5499,
14036,
364,
7720,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
5782,
281,
3245,
288,
203,
3639,
2874,
12,
2867,
516,
467,
2954,
281,
11137,
18,
11476,
639,
14667,
966,
13,
11301,
639,
774,
14667,
966,
31,
203,
3639,
2254,
5034,
534,
17616,
8201,
14667,
31,
203,
3639,
2254,
5034,
5499,
9220,
14667,
31,
203,
3639,
1758,
14036,
56,
266,
3619,
31,
203,
3639,
1426,
6454,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
*
*
* http://fairdapp.com http://fairdapp.com http://fairdapp.com
*
* _______ _ ______ _______ ______ ______
* (_______) (_) (______)(_______|_____ (_____ \
* _____ _____ _ ____ _ _ _______ _____) )____) )
* | ___|____ | |/ ___) | | | ___ | ____/ ____/
* | | / ___ | | | | |__/ /| | | | | | |
* |_| \_____|_|_| |_____/ |_| |_|_| |_|
*
* _ ___ _ _
* | | / __|_) (_) _
* | |____ _| |__ _ ____ _ _| |_ _ _
* | | _ (_ __) | _ \| (_ _) | | |
* | | | | || | | | | | | | | |_| |_| |
* |_|_| |_||_| |_|_| |_|_| \__)\__ |
* (____/
*
* Warning:
*
* FairDAPP – Infinity is a system designed to explore human behavior
* using infinite loops of token redistribution through open source
* smart contract codes and pre-defined rules.
*
* This system is for internal use only and all could be lost
* by sending anything to this contract address.
*
* -The contract has an activation switch to activate the system.
* -No one can change anything once the contract has been deployed.
*
* -Built in Antiwhale for initial stages for a fairer system.
*
**/
contract Infinity {
using SafeMath for uint256;
/*------------------------------
CONFIGURABLES
------------------------------*/
string public name = "Infinity"; // Contract name
string public symbol = "Inf";
uint256 public initAmount; // Initial stage target
uint256 public amountProportion; // Stage target growth rate %
uint256 public dividend; // Input to Dividend %
uint256 public jackpot; // Input to Jackpot %
uint256 public jackpotProportion; // Jackpot payout %
uint256 public scientists; // Donation Fee % to scientists
uint256 public promotionRatio; // Promotion %
uint256 public duration; // Duration per stage
bool public activated = false;
address public developerAddr;
/*------------------------------
DATASETS
------------------------------*/
uint256 public rId; // Current round id number
uint256 public sId; // Current stage id number
mapping (uint256 => Indatasets.Round) public round; // (rId => data) round data by round id
mapping (uint256 => mapping (uint256 => Indatasets.Stage)) public stage; // (rId => sId => data) stage data by round id & stage id
mapping (address => Indatasets.Player) public player; // (address => data) player data
mapping (uint256 => mapping (address => uint256)) public playerRoundAmount; // (rId => address => playerRoundAmount) round data by round id
mapping (uint256 => mapping (address => uint256)) public playerRoundSid;
mapping (uint256 => mapping (address => uint256)) public playerRoundwithdrawAmountFlag;
mapping (uint256 => mapping (uint256 => mapping (address => uint256))) public playerStageAmount; // (rId => sId => address => playerStageAmount) round data by round id & stage id
mapping (uint256 => mapping (uint256 => mapping (address => uint256))) public playerStageAccAmount;
//Antiwhale setting, max 5% of stage target for the first 10 stages per address
uint256[] amountLimit = [0, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50];
/*------------------------------
PUBLIC FUNCTIONS
------------------------------*/
constructor()
public
{
developerAddr = msg.sender;
}
/*------------------------------
MODIFIERS
------------------------------*/
modifier isActivated() {
require(activated == true, "its not ready yet. check ?eta in discord");
_;
}
modifier senderVerify() {
require (msg.sender == tx.origin);
_;
}
modifier stageVerify(uint256 _rId, uint256 _sId, uint256 _amount) {
require(stage[_rId][_sId].amount.add(_amount) <= stage[_rId][_sId].targetAmount);
_;
}
/**
* Don't toy or spam the contract.
* The scientists will take anything below 0.0001 ETH sent to the contract.
* Thank you for your donation.
*/
modifier amountVerify() {
if(msg.value < 100000000000000){
developerAddr.transfer(msg.value);
}else{
require(msg.value >= 100000000000000);
_;
}
}
modifier playerVerify() {
require(player[msg.sender].active == true);
_;
}
/**
* Activation of contract with settings
*/
function activate()
public
{
require(msg.sender == developerAddr);
require(activated == false, "Infinity already activated");
activated = true;
initAmount = 10000000000000000000;
amountProportion = 10;
dividend = 70;
jackpot = 28;
jackpotProportion = 70;
scientists = 2;
promotionRatio = 10;
duration = 86400;
rId = 1;
sId = 1;
round[rId].start = now;
initStage(rId, sId);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
isActivated()
senderVerify()
amountVerify()
payable
public
{
buyAnalysis(0x0);
}
/**
* Standard buy function.
*/
function buy(address _recommendAddr)
isActivated()
senderVerify()
amountVerify()
public
payable
returns(uint256)
{
buyAnalysis(_recommendAddr);
}
/**
* Withdraw function.
* Withdraw 50 stages at once on current settings.
* May require to request withdraw more than once to withdraw everything.
*/
function withdraw()
isActivated()
senderVerify()
playerVerify()
public
{
uint256 _rId = rId;
uint256 _sId = sId;
uint256 _amount;
uint256 _playerWithdrawAmountFlag;
(_amount, player[msg.sender].withdrawRid, player[msg.sender].withdrawSid, _playerWithdrawAmountFlag) = getPlayerDividendByStage(_rId, _sId, msg.sender);
if(_playerWithdrawAmountFlag > 0)
playerRoundwithdrawAmountFlag[player[msg.sender].withdrawRid][msg.sender] = _playerWithdrawAmountFlag;
if(player[msg.sender].promotionAmount > 0 ){
_amount = _amount.add(player[msg.sender].promotionAmount);
player[msg.sender].promotionAmount = 0;
}
msg.sender.transfer(_amount);
}
/**
* Core logic to analyse buy behaviour.
*/
function buyAnalysis(address _recommendAddr)
private
{
uint256 _rId = rId;
uint256 _sId = sId;
uint256 _amount = msg.value;
uint256 _promotionRatio = promotionRatio;
if(now > stage[_rId][_sId].end && stage[_rId][_sId].targetAmount > stage[_rId][_sId].amount){
endRound(_rId, _sId);
_rId = rId;
_sId = sId;
round[_rId].start = now;
initStage(_rId, _sId);
_amount = limitAmount(_rId, _sId);
buyRoundDataRecord(_rId, _amount);
_promotionRatio = promotionDataRecord(_recommendAddr, _amount);
buyStageDataRecord(_rId, _sId, _promotionRatio, _amount);
buyPlayerDataRecord(_rId, _sId, _amount);
}else if(now <= stage[_rId][_sId].end){
_amount = limitAmount(_rId, _sId);
buyRoundDataRecord(_rId, _amount);
_promotionRatio = promotionDataRecord(_recommendAddr, _amount);
if(stage[_rId][_sId].amount.add(_amount) >= stage[_rId][_sId].targetAmount){
uint256 differenceAmount = (stage[_rId][_sId].targetAmount).sub(stage[_rId][_sId].amount);
buyStageDataRecord(_rId, _sId, _promotionRatio, differenceAmount);
buyPlayerDataRecord(_rId, _sId, differenceAmount);
endStage(_rId, _sId);
_sId = sId;
initStage(_rId, _sId);
round[_rId].endSid = _sId;
buyStageDataRecord(_rId, _sId, _promotionRatio, _amount.sub(differenceAmount));
buyPlayerDataRecord(_rId, _sId, _amount.sub(differenceAmount));
}else{
buyStageDataRecord(_rId, _sId, _promotionRatio, _amount);
buyPlayerDataRecord(_rId, _sId, _amount);
}
}
}
/**
* Sets the initial stage parameter.
*/
function initStage(uint256 _rId, uint256 _sId)
private
{
uint256 _targetAmount;
stage[_rId][_sId].start = now;
stage[_rId][_sId].end = now.add(duration);
if(_sId > 1){
stage[_rId][_sId - 1].end = now;
stage[_rId][_sId - 1].ended = true;
_targetAmount = (stage[_rId][_sId - 1].targetAmount.mul(amountProportion + 100)) / 100;
}else
_targetAmount = initAmount;
stage[_rId][_sId].targetAmount = _targetAmount;
}
/**
* Execution of antiwhale.
*/
function limitAmount(uint256 _rId, uint256 _sId)
private
returns(uint256)
{
uint256 _amount = msg.value;
if(amountLimit.length > _sId)
_amount = ((stage[_rId][_sId].targetAmount.mul(amountLimit[_sId])) / 1000).sub(playerStageAmount[_rId][_sId][msg.sender]);
else
_amount = ((stage[_rId][_sId].targetAmount.mul(500)) / 1000).sub(playerStageAmount[_rId][_sId][msg.sender]);
if(_amount >= msg.value)
return msg.value;
else
msg.sender.transfer(msg.value.sub(_amount));
return _amount;
}
/**
* Record the addresses eligible for promotion links.
*/
function promotionDataRecord(address _recommendAddr, uint256 _amount)
private
returns(uint256)
{
uint256 _promotionRatio = promotionRatio;
if(_recommendAddr != 0x0000000000000000000000000000000000000000
&& _recommendAddr != msg.sender
&& player[_recommendAddr].active == true
)
player[_recommendAddr].promotionAmount = player[_recommendAddr].promotionAmount.add((_amount.mul(_promotionRatio)) / 100);
else
_promotionRatio = 0;
return _promotionRatio;
}
/**
* Records the round data.
*/
function buyRoundDataRecord(uint256 _rId, uint256 _amount)
private
{
round[_rId].amount = round[_rId].amount.add(_amount);
developerAddr.transfer(_amount.mul(scientists) / 100);
}
/**
* Records the stage data.
*/
function buyStageDataRecord(uint256 _rId, uint256 _sId, uint256 _promotionRatio, uint256 _amount)
stageVerify(_rId, _sId, _amount)
private
{
if(_amount <= 0)
return;
stage[_rId][_sId].amount = stage[_rId][_sId].amount.add(_amount);
stage[_rId][_sId].dividendAmount = stage[_rId][_sId].dividendAmount.add((_amount.mul(dividend.sub(_promotionRatio))) / 100);
}
/**
* Records the player data.
*/
function buyPlayerDataRecord(uint256 _rId, uint256 _sId, uint256 _amount)
private
{
if(_amount <= 0)
return;
if(player[msg.sender].active == false){
player[msg.sender].active = true;
player[msg.sender].withdrawRid = _rId;
player[msg.sender].withdrawSid = _sId;
}
if(playerRoundAmount[_rId][msg.sender] == 0){
round[_rId].players++;
playerRoundSid[_rId][msg.sender] = _sId;
}
if(playerStageAmount[_rId][_sId][msg.sender] == 0)
stage[_rId][_sId].players++;
playerRoundAmount[_rId][msg.sender] = playerRoundAmount[_rId][msg.sender].add(_amount);
playerStageAmount[_rId][_sId][msg.sender] = playerStageAmount[_rId][_sId][msg.sender].add(_amount);
player[msg.sender].amount = player[msg.sender].amount.add(_amount);
if(playerRoundSid[_rId][msg.sender] > 0){
if(playerStageAccAmount[_rId][_sId][msg.sender] == 0){
for(uint256 i = playerRoundSid[_rId][msg.sender]; i < _sId; i++){
if(playerStageAmount[_rId][i][msg.sender] > 0)
playerStageAccAmount[_rId][_sId][msg.sender] = playerStageAccAmount[_rId][_sId][msg.sender].add(playerStageAmount[_rId][i][msg.sender]);
}
}
playerStageAccAmount[_rId][_sId][msg.sender] = playerStageAccAmount[_rId][_sId][msg.sender].add(_amount);
}
}
/**
* Execute end of round events.
*/
function endRound(uint256 _rId, uint256 _sId)
private
{
round[_rId].end = now;
round[_rId].ended = true;
round[_rId].endSid = _sId;
stage[_rId][_sId].end = now;
stage[_rId][_sId].ended = true;
if(stage[_rId][_sId].players == 0)
round[_rId + 1].jackpotAmount = round[_rId + 1].jackpotAmount.add(round[_rId].jackpotAmount);
else
round[_rId + 1].jackpotAmount = round[_rId + 1].jackpotAmount.add(round[_rId].jackpotAmount.mul(100 - jackpotProportion) / 100);
rId++;
sId = 1;
}
/**
* Execute end of stage events.
*/
function endStage(uint256 _rId, uint256 _sId)
private
{
uint256 _jackpotAmount = stage[_rId][_sId].amount.mul(jackpot) / 100;
round[_rId].endSid = _sId;
round[_rId].jackpotAmount = round[_rId].jackpotAmount.add(_jackpotAmount);
stage[_rId][_sId].end = now;
stage[_rId][_sId].ended = true;
if(_sId > 1)
stage[_rId][_sId].accAmount = stage[_rId][_sId].targetAmount.add(stage[_rId][_sId - 1].accAmount);
else
stage[_rId][_sId].accAmount = stage[_rId][_sId].targetAmount;
sId++;
}
/**
* Precalculations for withdraws to conserve gas.
*/
function getPlayerDividendByStage(uint256 _rId, uint256 _sId, address _playerAddr)
private
view
returns(uint256, uint256, uint256, uint256)
{
uint256 _dividend;
uint256 _stageNumber;
uint256 _startSid;
uint256 _playerAmount;
for(uint256 i = player[_playerAddr].withdrawRid; i <= _rId; i++){
if(playerRoundAmount[i][_playerAddr] == 0)
continue;
_playerAmount = 0;
_startSid = i == player[_playerAddr].withdrawRid ? player[_playerAddr].withdrawSid : 1;
for(uint256 j = _startSid; j < round[i].endSid; j++){
if(playerStageAccAmount[i][j][_playerAddr] > 0)
_playerAmount = playerStageAccAmount[i][j][_playerAddr];
if(_playerAmount == 0)
_playerAmount = playerRoundwithdrawAmountFlag[i][_playerAddr];
if(_playerAmount == 0)
continue;
_dividend = _dividend.add(
(
_playerAmount.mul(stage[i][j].dividendAmount)
).div(stage[i][j].accAmount)
);
_stageNumber++;
if(_stageNumber >= 50)
return (_dividend, i, j + 1, _playerAmount);
}
if(round[i].ended == true
&& stage[i][round[i].endSid].amount > 0
&& playerStageAmount[i][round[i].endSid][_playerAddr] > 0
){
_dividend = _dividend.add(getPlayerJackpot(_playerAddr, i));
_stageNumber++;
if(_stageNumber >= 50)
return (_dividend, i + 1, 1, 0);
}
}
return (_dividend, _rId, _sId, _playerAmount);
}
/**
* Get player current withdrawable dividend.
*/
function getPlayerDividend(address _playerAddr)
public
view
returns(uint256)
{
uint256 _endRid = rId;
uint256 _startRid = player[_playerAddr].withdrawRid;
uint256 _startSid;
uint256 _dividend;
for(uint256 i = _startRid; i <= _endRid; i++){
if(i == _startRid)
_startSid = player[_playerAddr].withdrawSid;
else
_startSid = 1;
_dividend = _dividend.add(getPlayerDividendByRound(_playerAddr, i, _startSid));
}
return _dividend;
}
/**
* Get player data for rounds and stages.
*/
function getPlayerDividendByRound(address _playerAddr, uint256 _rId, uint256 _sId)
public
view
returns(uint256)
{
uint256 _dividend;
uint256 _startSid = _sId;
uint256 _endSid = round[_rId].endSid;
uint256 _playerAmount;
uint256 _totalAmount;
for(uint256 i = _startSid; i < _endSid; i++){
if(stage[_rId][i].ended == false)
continue;
_playerAmount = 0;
_totalAmount = 0;
for(uint256 j = 1; j <= i; j++){
if(playerStageAmount[_rId][j][_playerAddr] > 0)
_playerAmount = _playerAmount.add(playerStageAmount[_rId][j][_playerAddr]);
_totalAmount = _totalAmount.add(stage[_rId][j].amount);
}
if(_playerAmount == 0 || stage[_rId][i].dividendAmount == 0)
continue;
_dividend = _dividend.add((_playerAmount.mul(stage[_rId][i].dividendAmount)).div(_totalAmount));
}
if(round[_rId].ended == true)
_dividend = _dividend.add(getPlayerJackpot(_playerAddr, _rId));
return _dividend;
}
/**
* Get player data for jackpot winnings.
*/
function getPlayerJackpot(address _playerAddr, uint256 _rId)
public
view
returns(uint256)
{
uint256 _dividend;
if(round[_rId].ended == false)
return _dividend;
uint256 _endSid = round[_rId].endSid;
uint256 _playerStageAmount = playerStageAmount[_rId][_endSid][_playerAddr];
uint256 _stageAmount = stage[_rId][_endSid].amount;
if(_stageAmount <= 0)
return _dividend;
uint256 _jackpotAmount = round[_rId].jackpotAmount.mul(jackpotProportion) / 100;
uint256 _stageDividendAmount = stage[_rId][_endSid].dividendAmount;
uint256 _stageJackpotAmount = (_stageAmount.mul(jackpot) / 100).add(_stageDividendAmount);
_dividend = _dividend.add(((_playerStageAmount.mul(_jackpotAmount)).div(_stageAmount)));
_dividend = _dividend.add(((_playerStageAmount.mul(_stageJackpotAmount)).div(_stageAmount)));
return _dividend;
}
/**
* For frontend.
*/
function getHeadInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, bool)
{
return
(
rId,
sId,
round[rId].jackpotAmount,
stage[rId][sId].targetAmount,
stage[rId][sId].amount,
stage[rId][sId].end,
stage[rId][sId].ended
);
}
/**
* For frontend.
*/
function getPersonalStatus(address _playerAddr)
public
view
returns(uint256, uint256, uint256)
{
if (player[_playerAddr].active == true){
return
(
round[rId].jackpotAmount,
playerRoundAmount[rId][_playerAddr],
getPlayerDividendByRound(_playerAddr, rId, 1)
);
}else{
return
(
round[rId].jackpotAmount,
0,
0
);
}
}
/**
* For frontend.
*/
function getValueInfo(address _playerAddr)
public
view
returns(uint256, uint256)
{
if (player[_playerAddr].active == true){
return
(
getPlayerDividend(_playerAddr),
player[_playerAddr].promotionAmount
);
}else{
return
(
0,
0
);
}
}
}
library Indatasets {
struct Round {
uint256 start; // time round started
uint256 end; // time round ends/ended
bool ended; // has round end function been ran
uint256 endSid; // last stage for current round
uint256 amount; // Eth recieved for current round
uint256 jackpotAmount; // total jackpot for current round
uint256 players; // total players for current round
}
struct Stage {
uint256 start; // time stage started
uint256 end; // time strage ends/ended
bool ended; // has stage end function been ran
uint256 targetAmount; // amount needed for current stage
uint256 amount; // Eth received for current stage
uint256 dividendAmount; // total dividend for current stage
uint256 accAmount; // total accumulative amount for current stage
uint256 players; // total players for current stage
}
struct Player {
bool active; // Activation status of player, if false player has not been activated.
uint256 amount; // Total player input.
uint256 promotionAmount; // Total promotion amount of the player.
uint256 withdrawRid; // Last withdraw round of the player.
uint256 withdrawSid; // Last withdraw stage of the player.
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @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;
}
/**
* @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 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 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);
}
}
} | has round end function been ran
| bool ended; | 1,718,743 | [
1,
5332,
3643,
679,
445,
2118,
18892,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1426,
16926,
31,
2868,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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/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/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/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: ERC721A.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal collectionSize;
uint256 internal maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}/*
function setmaxBatchSize(uint256 newBatch)public onlyOwner{
maxBatchSize = newBatch;
}*/
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// 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: SoulSquadsVIP.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract SoulSquadsVIP is Ownable, ERC721A, ReentrancyGuard {
uint256 public cost = 0.08 ether;
uint256 public nftPerAddressLimit = 4;
uint256 public MAX_BATCH_SIZE = nftPerAddressLimit;
uint256 public maxSupply = 222;
address private teamAddress = 0x7cC29101b5B737268517dCe3f500556B0E901d95;
address[] public whitelistedAddresses;
mapping(address => uint256) public addressMintCount;
bool public isPresaleLive = true;
bool public paused = true;
bool public revealed = false;
string public _baseTokenURI = "https://soulsquads.io/";
string public notRevealedUri = "https://soulsquads.io/";
string public baseExtension = ".json";
string constant public longName = "SoulSquads VIP";
string constant public shortName = "Souly";
constructor() ERC721A(longName, shortName, MAX_BATCH_SIZE, maxSupply) {}
modifier mintGuard(uint256 tokenCount) {
require(msg.sender == tx.origin, "No cheating");
require(totalSupply() + tokenCount <= maxSupply, "Not enough supply");
if (msg.sender != owner()){
require(cost * tokenCount <= msg.value, "Wrong ether value");
require(tokenCount <= nftPerAddressLimit, "Exceeds token txn limit ");
}
_;
}
function isWhitelisted(address _user) public view returns(bool){
for(uint256 i = 0; i < whitelistedAddresses.length;i++){
if(whitelistedAddresses[i] == _user){
return true;
}
}
return false;
}
function whitelistUsers(address[] calldata _users) public onlyOwner {
delete whitelistedAddresses;
whitelistedAddresses = _users;
}
function mint(uint256 amount) external payable mintGuard(amount) {
if (msg.sender != owner()) {
require(!paused);
if(isPresaleLive == true){
require(isWhitelisted(msg.sender),"User is not whitelisted.");
}
require(addressMintCount[msg.sender] + amount <= nftPerAddressLimit, "Address already minted allocation");
addressMintCount[msg.sender] += amount;
}
_safeMint(msg.sender, amount);
}
function resetAddressMintCount() public onlyOwner {
for(uint256 a = 0; a < whitelistedAddresses.length; a++){
addressMintCount[whitelistedAddresses[a]] = 0;
}
}
function flipPaused() external onlyOwner {
paused = !paused;
}
function flipReveald() external onlyOwner {
revealed = !revealed;
}
function flipPresaleState() external onlyOwner {
isPresaleLive = !isPresaleLive;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function setNotRevealedUri(string calldata _notRevealedUri) external onlyOwner {
notRevealedUri = _notRevealedUri;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setcost(uint256 newcost)external onlyOwner{
cost = newcost;
}
function setnftPerAddressLimit(uint256 newAmount)external onlyOwner{
nftPerAddressLimit = newAmount;
}
function setTeamAddress(address newAddress)external onlyOwner{
teamAddress = newAddress;
}
function setmaxSupply(uint256 newSupply)external onlyOwner{
maxSupply = newSupply;
}
function withdraw() external onlyOwner {
payable(teamAddress).transfer(address(this).balance);
}
function getOwner(uint256 id)public view returns(address){
return this.ownerOf(id);
}
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 = _baseTokenURI;
string memory tokenIdString = Strings.toString(tokenId);
return bytes(currentBaseURI).length > 0
//? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
? string(abi.encodePacked(currentBaseURI, tokenIdString, baseExtension))
: "";
}
event Received(address, uint);
receive() external payable {
emit Received(msg.sender, msg.value);
}
} | * @dev Mints `quantity` tokens and transfers them to `to`. Requirements: - there must be `quantity` tokens remaining unminted in the total collection. - `to` cannot be the zero address. - `quantity` cannot be larger than the max batch size. Emits a {Transfer} event./ We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. | function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
| 13,803,157 | [
1,
49,
28142,
1375,
16172,
68,
2430,
471,
29375,
2182,
358,
1375,
869,
8338,
29076,
30,
300,
1915,
1297,
506,
1375,
16172,
68,
2430,
4463,
27701,
474,
329,
316,
326,
2078,
1849,
18,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
16172,
68,
2780,
506,
10974,
2353,
326,
943,
2581,
963,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
19,
1660,
5055,
309,
326,
1122,
1147,
316,
326,
2581,
3302,
1404,
1005,
16,
326,
1308,
5945,
2727,
1404,
487,
5492,
16,
2724,
434,
2734,
9543,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
915,
389,
4626,
49,
474,
12,
203,
225,
1758,
358,
16,
203,
225,
2254,
5034,
10457,
16,
203,
225,
1731,
3778,
389,
892,
203,
13,
2713,
288,
203,
225,
2254,
5034,
787,
1345,
548,
273,
17032,
31,
203,
225,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
27,
5340,
37,
30,
312,
474,
358,
326,
3634,
1758,
8863,
203,
225,
2583,
12,
5,
67,
1808,
12,
1937,
1345,
548,
3631,
315,
654,
39,
27,
5340,
37,
30,
1147,
1818,
312,
474,
329,
8863,
203,
225,
2583,
12,
16172,
1648,
943,
23304,
16,
315,
654,
39,
27,
5340,
37,
30,
10457,
358,
312,
474,
4885,
3551,
8863,
203,
225,
389,
5771,
1345,
1429,
18881,
12,
2867,
12,
20,
3631,
358,
16,
787,
1345,
548,
16,
10457,
1769,
203,
225,
5267,
751,
3778,
1758,
751,
273,
389,
2867,
751,
63,
869,
15533,
203,
225,
389,
2867,
751,
63,
869,
65,
273,
5267,
751,
12,
203,
565,
1758,
751,
18,
12296,
397,
2254,
10392,
12,
16172,
3631,
203,
565,
1758,
751,
18,
2696,
49,
474,
329,
397,
2254,
10392,
12,
16172,
13,
203,
225,
11272,
203,
225,
389,
995,
12565,
87,
63,
1937,
1345,
548,
65,
273,
3155,
5460,
12565,
12,
869,
16,
2254,
1105,
12,
2629,
18,
5508,
10019,
203,
225,
2254,
5034,
3526,
1016,
273,
787,
1345,
548,
31,
203,
225,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
10457,
31,
277,
27245,
288,
203,
565,
3626,
12279,
12,
2867,
12,
20,
3631,
358,
16,
3526,
1016,
1769,
203,
565,
2
] |
// https://github.com/iearn-finance/globes/blob/master/contracts/controllers/StrategyControllerV1.sol
pragma solidity ^0.6.7;
pragma experimental ABIEncoderV2;
import "./interfaces/controller.sol";
import "./lib/erc20.sol";
import "./lib/safe-math.sol";
import "./interfaces/globe.sol";
import "./interfaces/globe-converter.sol";
import "./interfaces/onesplit.sol";
import "./interfaces/strategy.sol";
import "./interfaces/converter.sol";
contract ControllerV4 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant burn = 0x000000000000000000000000000000000000dEaD;
address public onesplit = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E;
address public governance;
address public strategist;
address public devfund;
address public treasury;
address public timelock;
// Convenience fee 0.1%
uint256 public convenienceFee = 100;
uint256 public constant convenienceFeeMax = 100000;
mapping(address => address) public globes; // takes lp address and returns associated globe
mapping(address => address) public strategies; // takes lp and returns associated strategy
mapping(address => mapping(address => address)) public converters;
mapping(address => mapping(address => bool)) public approvedStrategies;
mapping(address => bool) public approvedGlobeConverters;
uint256 public split = 500;
uint256 public constant max = 10000;
constructor(
address _governance,
address _strategist,
address _timelock,
address _devfund,
address _treasury
) public {
governance = _governance;
strategist = _strategist;
timelock = _timelock;
devfund = _devfund;
treasury = _treasury;
}
function setDevFund(address _devfund) public {
require(msg.sender == governance, "!governance");
devfund = _devfund;
}
function setTreasury(address _treasury) public {
require(msg.sender == governance, "!governance");
treasury = _treasury;
}
function setStrategist(address _strategist) public {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function setSplit(uint256 _split) public {
require(msg.sender == governance, "!governance");
require(_split <= max, "numerator cannot be greater than denominator");
split = _split;
}
function setOneSplit(address _onesplit) public {
require(msg.sender == governance, "!governance");
onesplit = _onesplit;
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setTimelock(address _timelock) public {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setGlobe(address _token, address _globe) public {
require(
msg.sender == strategist || msg.sender == governance,
"!strategist"
);
require(globes[_token] == address(0), "globe");
globes[_token] = _globe;
}
function approveGlobeConverter(address _converter) public {
require(msg.sender == governance, "!governance");
approvedGlobeConverters[_converter] = true;
}
function revokeGlobeConverter(address _converter) public {
require(msg.sender == governance, "!governance");
approvedGlobeConverters[_converter] = false;
}
function approveStrategy(address _token, address _strategy) public {
require(msg.sender == timelock, "!timelock");
approvedStrategies[_token][_strategy] = true;
}
function revokeStrategy(address _token, address _strategy) public {
require(msg.sender == governance, "!governance");
require(strategies[_token] != _strategy, "cannot revoke active strategy");
approvedStrategies[_token][_strategy] = false;
}
function setConvenienceFee(uint256 _convenienceFee) external {
require(msg.sender == timelock, "!timelock");
convenienceFee = _convenienceFee;
}
function setStrategy(address _token, address _strategy) public {
require(
msg.sender == strategist || msg.sender == governance,
"!strategist"
);
require(approvedStrategies[_token][_strategy] == true, "!approved");
address _current = strategies[_token];
if (_current != address(0)) {
IStrategy(_current).withdrawAll();
}
strategies[_token] = _strategy;
}
function earn(address _token, uint256 _amount) public {
address _strategy = strategies[_token];
address _want = IStrategy(_strategy).want();
if (_want != _token) {
address converter = converters[_token][_want];
IERC20(_token).safeTransfer(converter, _amount);
_amount = Converter(converter).convert(_strategy);
IERC20(_want).safeTransfer(_strategy, _amount);
} else {
IERC20(_token).safeTransfer(_strategy, _amount);
}
IStrategy(_strategy).deposit();
}
function balanceOf(address _token) external view returns (uint256) {
return IStrategy(strategies[_token]).balanceOf();
}
function withdrawAll(address _token) public {
require(
msg.sender == strategist || msg.sender == governance,
"!strategist"
);
IStrategy(strategies[_token]).withdrawAll();
}
function inCaseTokensGetStuck(address _token, uint256 _amount) public {
require(
msg.sender == strategist || msg.sender == governance,
"!governance"
);
IERC20(_token).safeTransfer(msg.sender, _amount);
}
function inCaseStrategyTokenGetStuck(address _strategy, address _token)
public
{
require(
msg.sender == strategist || msg.sender == governance,
"!governance"
);
IStrategy(_strategy).withdraw(_token);
}
function getExpectedReturn(
address _strategy,
address _token,
uint256 parts
) public view returns (uint256 expected) {
uint256 _balance = IERC20(_token).balanceOf(_strategy);
address _want = IStrategy(_strategy).want();
(expected, ) = OneSplitAudit(onesplit).getExpectedReturn(
_token,
_want,
_balance,
parts,
0
);
}
// Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield
function yearn(
address _strategy,
address _token,
uint256 parts
) public {
require(
msg.sender == strategist || msg.sender == governance,
"!governance"
);
// This contract should never have value in it, but just incase since this is a public call
uint256 _before = IERC20(_token).balanceOf(address(this));
IStrategy(_strategy).withdraw(_token);
uint256 _after = IERC20(_token).balanceOf(address(this));
if (_after > _before) {
uint256 _amount = _after.sub(_before);
address _want = IStrategy(_strategy).want();
uint256[] memory _distribution;
uint256 _expected;
_before = IERC20(_want).balanceOf(address(this));
IERC20(_token).safeApprove(onesplit, 0);
IERC20(_token).safeApprove(onesplit, _amount);
(_expected, _distribution) = OneSplitAudit(onesplit)
.getExpectedReturn(_token, _want, _amount, parts, 0);
OneSplitAudit(onesplit).swap(
_token,
_want,
_amount,
_expected,
_distribution,
0
);
_after = IERC20(_want).balanceOf(address(this));
if (_after > _before) {
_amount = _after.sub(_before);
uint256 _treasury = _amount.mul(split).div(max);
earn(_want, _amount.sub(_treasury));
IERC20(_want).safeTransfer(treasury, _treasury);
}
}
}
function withdraw(address _token, uint256 _amount) public {
require(msg.sender == globes[_token], "!globe");
IStrategy(strategies[_token]).withdraw(_amount);
}
// Function to swap between globes
function swapExactGlobeForGlobe(
address _fromGlobe, // From which Globe
address _toGlobe, // To which Globe
uint256 _fromGlobeAmount, // How much globe tokens to swap
uint256 _toGlobeMinAmount, // How much globe tokens you'd like at a minimum
address payable[] calldata _targets,
bytes[] calldata _data
) external returns (uint256) {
require(_targets.length == _data.length, "!length");
// Only return last response
for (uint256 i = 0; i < _targets.length; i++) {
require(_targets[i] != address(0), "!converter");
require(approvedGlobeConverters[_targets[i]], "!converter");
}
address _fromGlobeToken = IGlobe(_fromGlobe).token();
address _toGlobeToken = IGlobe(_toGlobe).token();
// Get pTokens from msg.sender
IERC20(_fromGlobe).safeTransferFrom(
msg.sender,
address(this),
_fromGlobeAmount
);
// Calculate how much underlying
// is the amount of pTokens worth
uint256 _fromGlobeUnderlyingAmount = _fromGlobeAmount
.mul(IGlobe(_fromGlobe).getRatio())
.div(10**uint256(IGlobe(_fromGlobe).decimals()));
// Call 'withdrawForSwap' on Globe's current strategy if Globe
// doesn't have enough initial capital.
// This has moves the funds from the strategy to the Globe's
// 'earnable' amount. Enabling 'free' withdrawals
uint256 _fromGlobeAvailUnderlying = IERC20(_fromGlobeToken).balanceOf(
_fromGlobe
);
if (_fromGlobeAvailUnderlying < _fromGlobeUnderlyingAmount) {
IStrategy(strategies[_fromGlobeToken]).withdrawForSwap(
_fromGlobeUnderlyingAmount.sub(_fromGlobeAvailUnderlying)
);
}
// Withdraw from Globe
// Note: this is free since its still within the "earnable" amount
// as we transferred the access
IERC20(_fromGlobe).safeApprove(_fromGlobe, 0);
IERC20(_fromGlobe).safeApprove(_fromGlobe, _fromGlobeAmount);
IGlobe(_fromGlobe).withdraw(_fromGlobeAmount);
// Calculate fee
uint256 _fromUnderlyingBalance = IERC20(_fromGlobeToken).balanceOf(
address(this)
);
uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div(
convenienceFeeMax
);
if (_convenienceFee > 1) {
IERC20(_fromGlobeToken).safeTransfer(devfund, _convenienceFee.div(2));
IERC20(_fromGlobeToken).safeTransfer(treasury, _convenienceFee.div(2));
}
// Executes sequence of logic
for (uint256 i = 0; i < _targets.length; i++) {
_execute(_targets[i], _data[i]);
}
// Deposit into new Globe
uint256 _toBal = IERC20(_toGlobeToken).balanceOf(address(this));
IERC20(_toGlobeToken).safeApprove(_toGlobe, 0);
IERC20(_toGlobeToken).safeApprove(_toGlobe, _toBal);
IGlobe(_toGlobe).deposit(_toBal);
// Send Globe Tokens to user
uint256 _toGlobeBal = IGlobe(_toGlobe).balanceOf(address(this));
if (_toGlobeBal < _toGlobeMinAmount) {
revert("!min-globe-amount");
}
IGlobe(_toGlobe).transfer(msg.sender, _toGlobeBal);
return _toGlobeBal;
}
function _execute(address _target, bytes memory _data)
internal
returns (bytes memory response)
{
require(_target != address(0), "!target");
// call contract in current context
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
0
)
let size := returndatasize()
response := mload(0x40)
mstore(
0x40,
add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))
)
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
}
}
| takes lp address and returns associated globe
| mapping(address => address) public globes; | 7,263,207 | [
1,
88,
3223,
12423,
1758,
471,
1135,
3627,
4715,
73,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
1758,
13,
1071,
4715,
281,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* This file is part of the 1st Solidity Gas Golfing Contest.
*
* This work is licensed under Creative Commons Attribution ShareAlike 3.0.
* https://creativecommons.org/licenses/by-sa/3.0/
*/
pragma solidity 0.4.24;
contract IndexOf {
/*
* @dev Returns the index of the first occurrence of `needle` in `haystack`,
* or -1 if `needle` is not found in `haystack`.
*
* Input strings may be of any length <2^255.
*
* @param haystack The string to search.
* @param needle The string to search for.
* @return The index of `needle` in `haystack`, or -1 if not found.
*/
// Total Gas Used: 1170817
function indexOf(string haystack, string needle) public pure returns(int) {
int potentialNeedle;
bytes memory string_rep2 = bytes(needle);
if(string_rep2.length == 0 || int(bytes(haystack).length) == 0 || (int(string_rep2.length) > int(bytes(haystack).length))) { return -1; }
bytes memory result = new bytes(string_rep2.length);
for(int y = 0; y < int(bytes(haystack).length); y++) {
if (bytes(haystack)[uint(y)] == string_rep2[0]) {
result[0] = bytes(haystack)[uint(y)];
potentialNeedle = y;
if(bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1] == string_rep2[uint(bytes(haystack).length) - 1]) {
result[string_rep2.length - 1] = bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1];
for(int z = potentialNeedle + 1; z < (int(string_rep2.length) - 1); z++) {
result[uint(z - potentialNeedle)] = bytes(haystack)[uint(z)];
}
}
}
if(keccak256(result) == keccak256(string_rep2)) { return potentialNeedle; }
}
return -1;
}
}
| Total Gas Used: 1170817 | contract IndexOf {
function indexOf(string haystack, string needle) public pure returns(int) {
int potentialNeedle;
bytes memory string_rep2 = bytes(needle);
bytes memory result = new bytes(string_rep2.length);
for(int y = 0; y < int(bytes(haystack).length); y++) {
if (bytes(haystack)[uint(y)] == string_rep2[0]) {
result[0] = bytes(haystack)[uint(y)];
potentialNeedle = y;
if(bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1] == string_rep2[uint(bytes(haystack).length) - 1]) {
result[string_rep2.length - 1] = bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1];
for(int z = potentialNeedle + 1; z < (int(string_rep2.length) - 1); z++) {
result[uint(z - potentialNeedle)] = bytes(haystack)[uint(z)];
}
}
}
}
return -1;
}
if(string_rep2.length == 0 || int(bytes(haystack).length) == 0 || (int(string_rep2.length) > int(bytes(haystack).length))) { return -1; }
function indexOf(string haystack, string needle) public pure returns(int) {
int potentialNeedle;
bytes memory string_rep2 = bytes(needle);
bytes memory result = new bytes(string_rep2.length);
for(int y = 0; y < int(bytes(haystack).length); y++) {
if (bytes(haystack)[uint(y)] == string_rep2[0]) {
result[0] = bytes(haystack)[uint(y)];
potentialNeedle = y;
if(bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1] == string_rep2[uint(bytes(haystack).length) - 1]) {
result[string_rep2.length - 1] = bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1];
for(int z = potentialNeedle + 1; z < (int(string_rep2.length) - 1); z++) {
result[uint(z - potentialNeedle)] = bytes(haystack)[uint(z)];
}
}
}
}
return -1;
}
function indexOf(string haystack, string needle) public pure returns(int) {
int potentialNeedle;
bytes memory string_rep2 = bytes(needle);
bytes memory result = new bytes(string_rep2.length);
for(int y = 0; y < int(bytes(haystack).length); y++) {
if (bytes(haystack)[uint(y)] == string_rep2[0]) {
result[0] = bytes(haystack)[uint(y)];
potentialNeedle = y;
if(bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1] == string_rep2[uint(bytes(haystack).length) - 1]) {
result[string_rep2.length - 1] = bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1];
for(int z = potentialNeedle + 1; z < (int(string_rep2.length) - 1); z++) {
result[uint(z - potentialNeedle)] = bytes(haystack)[uint(z)];
}
}
}
}
return -1;
}
function indexOf(string haystack, string needle) public pure returns(int) {
int potentialNeedle;
bytes memory string_rep2 = bytes(needle);
bytes memory result = new bytes(string_rep2.length);
for(int y = 0; y < int(bytes(haystack).length); y++) {
if (bytes(haystack)[uint(y)] == string_rep2[0]) {
result[0] = bytes(haystack)[uint(y)];
potentialNeedle = y;
if(bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1] == string_rep2[uint(bytes(haystack).length) - 1]) {
result[string_rep2.length - 1] = bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1];
for(int z = potentialNeedle + 1; z < (int(string_rep2.length) - 1); z++) {
result[uint(z - potentialNeedle)] = bytes(haystack)[uint(z)];
}
}
}
}
return -1;
}
function indexOf(string haystack, string needle) public pure returns(int) {
int potentialNeedle;
bytes memory string_rep2 = bytes(needle);
bytes memory result = new bytes(string_rep2.length);
for(int y = 0; y < int(bytes(haystack).length); y++) {
if (bytes(haystack)[uint(y)] == string_rep2[0]) {
result[0] = bytes(haystack)[uint(y)];
potentialNeedle = y;
if(bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1] == string_rep2[uint(bytes(haystack).length) - 1]) {
result[string_rep2.length - 1] = bytes(haystack)[uint(potentialNeedle) + string_rep2.length - 1];
for(int z = potentialNeedle + 1; z < (int(string_rep2.length) - 1); z++) {
result[uint(z - potentialNeedle)] = bytes(haystack)[uint(z)];
}
}
}
}
return -1;
}
if(keccak256(result) == keccak256(string_rep2)) { return potentialNeedle; }
}
| 6,375,731 | [
1,
5269,
31849,
10286,
30,
27894,
6840,
4033,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3340,
951,
288,
203,
203,
203,
203,
565,
445,
3133,
12,
1080,
13764,
16,
533,
9936,
13,
1071,
16618,
1135,
12,
474,
13,
288,
203,
3639,
509,
8555,
14112,
298,
31,
203,
3639,
1731,
3778,
533,
67,
14462,
22,
273,
1731,
12,
14891,
298,
1769,
203,
3639,
1731,
3778,
563,
273,
394,
1731,
12,
1080,
67,
14462,
22,
18,
2469,
1769,
203,
3639,
364,
12,
474,
677,
273,
374,
31,
677,
411,
509,
12,
3890,
12,
76,
12582,
2934,
2469,
1769,
677,
27245,
288,
203,
5411,
309,
261,
3890,
12,
76,
12582,
25146,
11890,
12,
93,
25887,
422,
533,
67,
14462,
22,
63,
20,
5717,
288,
203,
7734,
563,
63,
20,
65,
273,
1731,
12,
76,
12582,
25146,
11890,
12,
93,
13,
15533,
203,
7734,
8555,
14112,
298,
273,
677,
31,
203,
7734,
309,
12,
3890,
12,
76,
12582,
25146,
11890,
12,
26451,
14112,
298,
13,
397,
533,
67,
14462,
22,
18,
2469,
300,
404,
65,
422,
533,
67,
14462,
22,
63,
11890,
12,
3890,
12,
76,
12582,
2934,
2469,
13,
300,
404,
5717,
288,
203,
10792,
563,
63,
1080,
67,
14462,
22,
18,
2469,
300,
404,
65,
273,
1731,
12,
76,
12582,
25146,
11890,
12,
26451,
14112,
298,
13,
397,
533,
67,
14462,
22,
18,
2469,
300,
404,
15533,
203,
10792,
364,
12,
474,
998,
273,
8555,
14112,
298,
397,
404,
31,
998,
411,
261,
474,
12,
1080,
67,
14462,
22,
18,
2469,
13,
300,
404,
1769,
998,
27245,
288,
203,
13491,
563,
63,
11890,
12,
94,
300,
8555,
14112,
298,
25887,
2
] |
./partial_match/3/0x6F6c9C4b558056Daa690229C837A21585f955448/sources/ECONToken.sol | lock marketing tokens - 1k tokens for 3 months (BLOCK)
| uint256 marketingReleaseTime = 1606742611; | 5,287,728 | [
1,
739,
13667,
310,
2430,
300,
404,
79,
2430,
364,
890,
8846,
261,
11403,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
13667,
310,
7391,
950,
273,
2872,
7677,
5608,
5558,
2499,
31,
4766,
4202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
contract MapElevationStorage
{
uint8[1089] elevations; // while this is a [a,b,c,d,a1,b1,c1,d1...] array, it should be thought of as
// [[a,b,c,d], [a1,b1,c1,d1]...] where each subarray is a column.
// since you'd access the subarray-style 2D array like this: col, row
// that means that in the 1D array, the first grouping is the first col. The second grouping is the second col, etc
// As such, element 1 is equivalent to 0,1 -- element 2 = 0,2 -- element 33 = 1,0 -- element 34 = 1,1
// this is a bit counter intuitive. You might think it would be arranged first row, second row, etc... but you'd be wrong.
address creator;
function MapElevationStorage()
{
creator = msg.sender;
}
function getElevations() constant returns (uint8[1089])
{
return elevations;
}
function getElevation(uint8 col, uint8 row) constant returns (uint8)
{
//uint index = col * 33 + row;
return elevations[uint(col) * 33 + uint(row)];
}
function initElevations(uint8 col, uint8[33] _elevations) public
{
if(locked) // lockout
return;
uint skip = (uint(col) * 33); // e.g. if row 2, start with element 66
uint counter = 0;
while(counter < 33)
{
elevations[counter+skip] = _elevations[counter];
counter++;
}
}
/**********
Standard lock-kill methods
**********/
bool locked;
function setLocked()
{
locked = true;
}
function getLocked() public constant returns (bool)
{
return locked;
}
function kill()
{
if (!locked && msg.sender == creator)
suicide(creator); // kills this contract and sends remaining funds back to creator
}
}
// address: 0x68549d7dbb7a956f955ec1263f55494f05972a6b
// transactionHash: 0x48a0c0eb350eba296e43d99a5f3c4394aa2a5da69e5369a58076f40fd32c9c99
/*
Solidity version: 0.1.6-d41f8b7c/.-Emscripten/clang/int linked to libethereum-
bytecode:
606060405261020b806100126000396000f3606060405260e060020a6000350463049b7852811461004757806310c1952f146100c45780632d49ffcd146100d65780634166c1fd146100e357806357f10d7114610122575b005b61016b61882060405190810160405280610441905b600081526020019060019003908161005c575050604080516188208101918290529060019061044190826000855b825461010083900a900460ff1681526020600192830181810494850194909303909202910180841161008a579050505050505090506100e0565b6100456000805460ff19166001179055565b61018660005460ff165b90565b6101986004356024356000600160ff84811660210290841601610441811015610002576020808204909201549190066101000a900460ff169392505050565b6040805161042081810190925261004591600480359290916104449190602490602190839083908082843750909550505050505060008054819060ff16156101af575b50505050565b60405180826188208083818460006004610cd2f15093505050f35b60408051918252519081900360200190f35b6040805160ff929092168252519081900360200190f35b505060ff821660210260005b60218110156101655782816021811015610002576020020151600183830161044181101561000257602080820483018054919092066101000a60ff810219909116930292909217909155016101bb56
abi
[{"constant":true,"inputs":[],"name":"getElevations","outputs":[{"name":"","type":"uint8[1089]"}],"type":"function"},{"constant":false,"inputs":[],"name":"setLocked","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"getLocked","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"col","type":"uint8"},{"name":"row","type":"uint8"}],"name":"getElevation","outputs":[{"name":"","type":"uint8"}],"type":"function"},{"constant":false,"inputs":[{"name":"col","type":"uint8"},{"name":"_elevations","type":"uint8[33]"}],"name":"initElevations","outputs":[],"type":"function"}]
web3 deploy
var mapelevationstorageContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"getElevations","outputs":[{"name":"","type":"uint8[1089]"}],"type":"function"},{"constant":false,"inputs":[],"name":"setLocked","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"getLocked","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"col","type":"uint8"},{"name":"row","type":"uint8"}],"name":"getElevation","outputs":[{"name":"","type":"uint8"}],"type":"function"},{"constant":false,"inputs":[{"name":"col","type":"uint8"},{"name":"_elevations","type":"uint8[33]"}],"name":"initElevations","outputs":[],"type":"function"}]);
var mapelevationstorage = mapelevationstorageContract.new(
{
from: web3.eth.accounts[0],
data: '606060405261020b806100126000396000f3606060405260e060020a6000350463049b7852811461004757806310c1952f146100c45780632d49ffcd146100d65780634166c1fd146100e357806357f10d7114610122575b005b61016b61882060405190810160405280610441905b600081526020019060019003908161005c575050604080516188208101918290529060019061044190826000855b825461010083900a900460ff1681526020600192830181810494850194909303909202910180841161008a579050505050505090506100e0565b6100456000805460ff19166001179055565b61018660005460ff165b90565b6101986004356024356000600160ff84811660210290841601610441811015610002576020808204909201549190066101000a900460ff169392505050565b6040805161042081810190925261004591600480359290916104449190602490602190839083908082843750909550505050505060008054819060ff16156101af575b50505050565b60405180826188208083818460006004610cd2f15093505050f35b60408051918252519081900360200190f35b6040805160ff929092168252519081900360200190f35b505060ff821660210260005b60218110156101655782816021811015610002576020020151600183830161044181101561000257602080820483018054919092066101000a60ff810219909116930292909217909155016101bb56',
gas: 3000000
}, function(e, contract){
if (typeof contract.address != 'undefined') {
console.log(e, contract);
console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
}
})
uDApp
[{"name":"MapElevationStorage","interface":"[{\"constant\":true,\"inputs\":[],\"name\":\"getElevations\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8[1089]\"}],\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"setLocked\",\"outputs\":[],\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getLocked\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"col\",\"type\":\"uint8\"},{\"name\":\"row\",\"type\":\"uint8\"}],\"name\":\"getElevation\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"col\",\"type\":\"uint8\"},{\"name\":\"_elevations\",\"type\":\"uint8[33]\"}],\"name\":\"initElevations\",\"outputs\":[],\"type\":\"function\"}]\n","bytecode":"606060405261020b806100126000396000f3606060405260e060020a6000350463049b7852811461004757806310c1952f146100c45780632d49ffcd146100d65780634166c1fd146100e357806357f10d7114610122575b005b61016b61882060405190810160405280610441905b600081526020019060019003908161005c575050604080516188208101918290529060019061044190826000855b825461010083900a900460ff1681526020600192830181810494850194909303909202910180841161008a579050505050505090506100e0565b6100456000805460ff19166001179055565b61018660005460ff165b90565b6101986004356024356000600160ff84811660210290841601610441811015610002576020808204909201549190066101000a900460ff169392505050565b6040805161042081810190925261004591600480359290916104449190602490602190839083908082843750909550505050505060008054819060ff16156101af575b50505050565b60405180826188208083818460006004610cd2f15093505050f35b60408051918252519081900360200190f35b6040805160ff929092168252519081900360200190f35b505060ff821660210260005b60218110156101655782816021811015610002576020020151600183830161044181101561000257602080820483018054919092066101000a60ff810219909116930292909217909155016101bb56"}]
*/
| [[a,b,c,d], [a1,b1,c1,d1]...] where each subarray is a column. since you'd access the subarray-style 2D array like this: col, row that means that in the 1D array, the first grouping is the first col. The second grouping is the second col, etc As such, element 1 is equivalent to 0,1 -- element 2 = 0,2 -- element 33 = 1,0 -- element 34 = 1,1 this is a bit counter intuitive. You might think it would be arranged first row, second row, etc... but you'd be wrong. | {
address creator;
function MapElevationStorage()
{
creator = msg.sender;
}
function getElevations() constant returns (uint8[1089])
{
return elevations;
}
function getElevation(uint8 col, uint8 row) constant returns (uint8)
{
return elevations[uint(col) * 33 + uint(row)];
}
function initElevations(uint8 col, uint8[33] _elevations) public
{
return;
uint counter = 0;
while(counter < 33)
{
elevations[counter+skip] = _elevations[counter];
counter++;
}
}
function initElevations(uint8 col, uint8[33] _elevations) public
{
return;
uint counter = 0;
while(counter < 33)
{
elevations[counter+skip] = _elevations[counter];
counter++;
}
}
Standard lock-kill methods
bool locked;
function setLocked()
{
locked = true;
}
function getLocked() public constant returns (bool)
{
return locked;
}
function kill()
{
if (!locked && msg.sender == creator)
}
}
| 1,824,064 | [
1,
31128,
69,
16,
70,
16,
71,
16,
72,
6487,
306,
69,
21,
16,
70,
21,
16,
71,
21,
16,
72,
21,
65,
2777,
65,
1625,
1517,
720,
1126,
353,
279,
1057,
18,
3241,
1846,
14271,
2006,
326,
720,
1126,
17,
4060,
576,
40,
526,
3007,
333,
30,
645,
16,
1027,
716,
4696,
716,
316,
326,
404,
40,
526,
16,
326,
1122,
12116,
353,
326,
1122,
645,
18,
1021,
2205,
12116,
353,
326,
2205,
645,
16,
5527,
2970,
4123,
16,
930,
404,
353,
7680,
358,
374,
16,
21,
1493,
930,
576,
273,
374,
16,
22,
1493,
930,
13159,
273,
404,
16,
20,
1493,
930,
13438,
273,
404,
16,
21,
333,
353,
279,
2831,
3895,
509,
89,
3720,
18,
4554,
4825,
15507,
518,
4102,
506,
2454,
2330,
1122,
1027,
16,
2205,
1027,
16,
5527,
2777,
1496,
1846,
14271,
506,
7194,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
565,
1758,
11784,
31,
203,
565,
445,
1635,
17274,
7112,
3245,
1435,
203,
565,
288,
203,
377,
202,
20394,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
377,
203,
565,
445,
4774,
298,
16882,
1435,
5381,
1135,
261,
11890,
28,
63,
2163,
6675,
5717,
203,
565,
288,
203,
377,
202,
2463,
5043,
16882,
31,
203,
565,
289,
203,
377,
203,
565,
445,
4774,
298,
7112,
12,
11890,
28,
645,
16,
2254,
28,
1027,
13,
5381,
1135,
261,
11890,
28,
13,
203,
565,
288,
203,
377,
202,
2463,
5043,
16882,
63,
11890,
12,
1293,
13,
380,
13159,
397,
2254,
12,
492,
13,
15533,
203,
565,
289,
203,
377,
203,
565,
445,
1208,
17274,
16882,
12,
11890,
28,
645,
16,
2254,
28,
63,
3707,
65,
389,
6516,
16882,
13,
1071,
7010,
565,
288,
203,
377,
202,
202,
2463,
31,
203,
377,
202,
11890,
3895,
273,
374,
31,
203,
377,
202,
17523,
12,
7476,
411,
13159,
13,
203,
377,
202,
95,
203,
377,
202,
202,
6516,
16882,
63,
7476,
15,
7457,
65,
273,
389,
6516,
16882,
63,
7476,
15533,
203,
377,
202,
202,
7476,
9904,
31,
203,
377,
202,
97,
202,
203,
565,
289,
203,
377,
203,
565,
445,
1208,
17274,
16882,
12,
11890,
28,
645,
16,
2254,
28,
63,
3707,
65,
389,
6516,
16882,
13,
1071,
7010,
565,
288,
203,
377,
202,
202,
2463,
31,
203,
377,
202,
11890,
3895,
273,
374,
31,
203,
377,
202,
17523,
12,
7476,
411,
13159,
13,
203,
377,
202,
95,
203,
377,
202,
202,
6516,
16882,
63,
2
] |
/**
*Submitted for verification at Etherscan.io on 2019-12-27
*/
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.5.12;
contract GemLike {
function allowance(address, address) public returns (uint);
function approve(address, uint) public;
function transfer(address, uint) public returns (bool);
function transferFrom(address, address, uint) public returns (bool);
}
contract ValueLike {
function peek() public returns (uint, bool);
}
contract SaiTubLike {
function skr() public view returns (GemLike);
function gem() public view returns (GemLike);
function gov() public view returns (GemLike);
function sai() public view returns (GemLike);
function pep() public view returns (ValueLike);
function vox() public view returns (VoxLike);
function bid(uint) public view returns (uint);
function ink(bytes32) public view returns (uint);
function tag() public view returns (uint);
function tab(bytes32) public returns (uint);
function rap(bytes32) public returns (uint);
function draw(bytes32, uint) public;
function shut(bytes32) public;
function exit(uint) public;
function give(bytes32, address) public;
}
contract VoxLike {
function par() public returns (uint);
}
contract JoinLike {
function ilk() public returns (bytes32);
function gem() public returns (GemLike);
function dai() public returns (GemLike);
function join(address, uint) public;
function exit(address, uint) public;
}
contract VatLike {
function ilks(bytes32) public view returns (uint, uint, uint, uint, uint);
function hope(address) public;
function frob(bytes32, address, address, address, int, int) public;
}
contract ManagerLike {
function vat() public view returns (address);
function urns(uint) public view returns (address);
function open(bytes32, address) public returns (uint);
function frob(uint, int, int) public;
function give(uint, address) public;
function move(uint, address, uint) public;
}
contract OtcLike {
function getPayAmount(address, address, uint) public view returns (uint);
function buyAllAmount(address, uint, address, uint) public;
}
/**
* Implements a "lock" feature with a cooldown
*/
library Blocklock {
struct State {
uint256 lockedAt;
uint256 unlockedAt;
uint256 lockDuration;
uint256 cooldownDuration;
}
function setLockDuration(State storage self, uint256 lockDuration) public {
require(lockDuration > 0, "Blocklock/lock-min");
self.lockDuration = lockDuration;
}
function setCooldownDuration(State storage self, uint256 cooldownDuration) public {
self.cooldownDuration = cooldownDuration;
}
function isLocked(State storage self, uint256 blockNumber) public view returns (bool) {
uint256 endAt = lockEndAt(self);
return (
self.lockedAt != 0 &&
blockNumber >= self.lockedAt &&
blockNumber < endAt
);
}
function lock(State storage self, uint256 blockNumber) public {
require(canLock(self, blockNumber), "Blocklock/no-lock");
self.lockedAt = blockNumber;
}
function unlock(State storage self, uint256 blockNumber) public {
self.unlockedAt = blockNumber;
}
function canLock(State storage self, uint256 blockNumber) public view returns (bool) {
uint256 endAt = lockEndAt(self);
return (
self.lockedAt == 0 ||
blockNumber >= endAt + self.cooldownDuration
);
}
function cooldownEndAt(State storage self) internal view returns (uint256) {
return lockEndAt(self) + self.cooldownDuration;
}
function lockEndAt(State storage self) internal view returns (uint256) {
uint256 endAt = self.lockedAt + self.lockDuration;
// if we unlocked early
if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) {
endAt = self.unlockedAt;
}
return endAt;
}
}
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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;
}
}
/**
* @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;
}
/**
* @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.
*/
contract ReentrancyGuard is Initializable {
// 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, "ReentrancyGuard: reentrant call");
}
uint256[50] private ______gap;
}
/**
* @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(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
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), "Roles: account is the zero address");
return role.bearer[account];
}
}
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
contract ICErc20 {
address public underlying;
function mint(uint mintAmount) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getCash() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
}
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @author Brendan Asselstine
* @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias.
* @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94
*/
library UniformRandomNumber {
/// @notice Select a random number without modulo bias using a random seed and upper bound
/// @param _entropy The seed for randomness
/// @param _upperBound The upper bound of the desired number
/// @return A random number less than the _upperBound
function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) {
if (_upperBound == 0) {
return 0;
}
uint256 min = -_upperBound % _upperBound;
uint256 random = _entropy;
while (true) {
if (random >= min) {
break;
}
random = uint256(keccak256(abi.encodePacked(random)));
}
return random % _upperBound;
}
}
/**
* @reviewers: [@clesaege, @unknownunknown1, @ferittuncer]
* @auditors: []
* @bounties: [<14 days 10 ETH max payout>]
* @deployments: []
*/
/**
* @title SortitionSumTreeFactory
* @author Enrique Piqueras - <[email protected]>
* @dev A factory of trees that keep track of staked values for sortition.
*/
library SortitionSumTreeFactory {
/* Structs */
struct SortitionSumTree {
uint K; // The maximum number of childs per node.
// We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around.
uint[] stack;
uint[] nodes;
// Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node.
mapping(bytes32 => uint) IDsToNodeIndexes;
mapping(uint => bytes32) nodeIndexesToIDs;
}
/* Storage */
struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
/* internal */
/**
* @dev Create a sortition sum tree at the specified key.
* @param _key The key of the new tree.
* @param _K The number of children each node in the tree should have.
*/
function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack.length = 0;
tree.nodes.length = 0;
tree.nodes.push(0);
}
/**
* @dev Set a value of a tree.
* @param _key The key of the tree.
* @param _value The new value.
* @param _ID The ID of the value.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (block.number == 0) { // No existing node. //injected CONTRACT AFFECTED BY MINERS
if (block.number != 0) { // Non zero value. //injected CONTRACT AFFECTED BY MINERS
// Append.
// Add node.
if (block.number == 0) { // No vacant spots. //injected CONTRACT AFFECTED BY MINERS
// Get the index and append the value.
treeIndex = tree.nodes.length;
tree.nodes.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child.
uint parentIndex = treeIndex / tree.K;
bytes32 parentID = tree.nodeIndexesToIDs[parentIndex];
uint newIndex = treeIndex + 1;
tree.nodes.push(tree.nodes[parentIndex]);
delete tree.nodeIndexesToIDs[parentIndex];
tree.IDsToNodeIndexes[parentID] = newIndex;
tree.nodeIndexesToIDs[newIndex] = parentID;
}
} else { // Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.length--;
tree.nodes[treeIndex] = _value;
}
// Add label.
tree.IDsToNodeIndexes[_ID] = treeIndex;
tree.nodeIndexesToIDs[treeIndex] = _ID;
updateParents(self, _key, treeIndex, true, _value);
}
} else { // Existing node.
if (block.number == 0) { // Zero value. //injected CONTRACT AFFECTED BY MINERS
// Remove.
// Remember value and set to 0.
uint value = tree.nodes[treeIndex];
tree.nodes[treeIndex] = 0;
// Push to stack.
tree.stack.push(treeIndex);
// Clear label.
delete tree.IDsToNodeIndexes[_ID];
delete tree.nodeIndexesToIDs[treeIndex];
updateParents(self, _key, treeIndex, false, value);
} else if (block.timestamp != tree.nodes[treeIndex]) { // New, non zero value. //injected CONTRACT AFFECTED BY MINERS
// Set.
bool plusOrMinus = tree.nodes[treeIndex] <= _value;
uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value;
tree.nodes[treeIndex] = _value;
updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue);
}
}
}
/* internal Views */
/**
* @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned.
* @param _key The key of the tree to get the leaves from.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination.
* `O(n)` where
* `n` is the maximum number of nodes ever appended.
*/
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count
) internal view returns(uint startIndex, uint[] memory values, bool hasMore) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
// Find the start index.
for (uint i = 0; i < tree.nodes.length; i++) {
if (block.number >= tree.nodes.length) { //injected CONTRACT AFFECTED BY MINERS
startIndex = i;
break;
}
}
// Get the values.
uint loopStartIndex = startIndex + _cursor;
values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count);
uint valuesIndex = 0;
for (uint j = loopStartIndex; j < tree.nodes.length; j++) {
if (block.timestamp < _count) { //injected CONTRACT AFFECTED BY MINERS
values[valuesIndex] = tree.nodes[j];
valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
/**
* @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.
* @param _key The key of the tree.
* @param _drawnNumber The drawn number.
* @return The drawn ID.
* `O(k * log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = 0;
uint currentDrawnNumber = _drawnNumber % tree.nodes[0];
while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children.
for (uint i = 1; i <= tree.K; i++) { // Loop over children.
uint nodeIndex = (tree.K * treeIndex) + i;
uint nodeValue = tree.nodes[nodeIndex];
if (block.timestamp >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. //injected CONTRACT AFFECTED BY MINERS
else { // Pick this child.
treeIndex = nodeIndex;
break;
}
}
ID = tree.nodeIndexesToIDs[treeIndex];
}
/** @dev Gets a specified ID's associated value.
* @param _key The key of the tree.
* @param _ID The ID of the value.
* @return The associated value.
*/
function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (block.gaslimit == 0) value = 0; //injected CONTRACT AFFECTED BY MINERS
else value = tree.nodes[treeIndex];
}
function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
return 0;
} else {
return tree.nodes[0];
}
}
/* Private */
/**
* @dev Update all the parents of a node.
* @param _key The key of the tree to update.
* @param _treeIndex The index of the node to start from.
* @param _plusOrMinus Wether to add (true) or substract (false).
* @param _value The value to add or substract.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value;
}
}
}
/**
* @author Brendan Asselstine
* @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances.
*
* Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw.
* When a new draw is opened, the previous opened draw is committed.
*
* The committed balance for an address is the total of their balances for committed Draws.
* An address's open balance is their balance in the open Draw.
*/
library DrawManager {
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
using SafeMath for uint256;
/**
* The ID to use for the selection tree.
*/
bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws";
uint8 public constant MAX_LEAVES = 10;
/**
* Stores information for all draws.
*/
struct State {
/**
* Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index.
* There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS.
*/
SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees;
/**
* Stores the first Draw index that an address deposited to.
*/
mapping(address => uint256) usersFirstDrawIndex;
/**
* Stores the last Draw index that an address deposited to.
*/
mapping(address => uint256) usersSecondDrawIndex;
/**
* Stores a mapping of Draw index => Draw total
*/
mapping(uint256 => uint256) __deprecated__drawTotals;
/**
* The current open Draw index
*/
uint256 openDrawIndex;
/**
* The total of committed balances
*/
uint256 __deprecated__committedSupply;
}
/**
* @notice Opens the next Draw and commits the previous open Draw (if any).
* @param self The drawState this library is attached to
* @return The index of the new open Draw
*/
function openNextDraw(State storage self) public returns (uint256) {
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
// If there is no previous draw, we must initialize
self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_LEAVES);
} else {
// else add current draw to sortition sum trees
bytes32 drawId = bytes32(self.openDrawIndex);
uint256 drawTotal = openSupply(self);
self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId);
}
// now create a new draw
uint256 drawIndex = self.openDrawIndex.add(1);
self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_LEAVES);
self.openDrawIndex = drawIndex;
return drawIndex;
}
/**
* @notice Deposits the given amount into the current open draw by the given user.
* @param self The DrawManager state
* @param _addr The address to deposit for
* @param _amount The amount to deposit
*/
function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openDrawIndex = self.openDrawIndex;
// update the current draw
uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId);
currentAmount = currentAmount.add(_amount);
drawSet(self, openDrawIndex, currentAmount, _addr);
uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr];
uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr];
// if this is the users first draw, set it
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
self.usersFirstDrawIndex[_addr] = openDrawIndex;
// otherwise, if the first draw is not this draw
} else if (block.gaslimit != openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS
// if a second draw does not exist
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
// set the second draw to the current draw
self.usersSecondDrawIndex[_addr] = openDrawIndex;
// otherwise if a second draw exists but is not the current one
} else if (block.timestamp != openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS
// merge it into the first draw, and update the second draw index to this one
uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId);
uint256 secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId);
drawSet(self, firstDrawIndex, firstAmount.add(secondAmount), _addr);
drawSet(self, secondDrawIndex, 0, _addr);
self.usersSecondDrawIndex[_addr] = openDrawIndex;
}
}
}
/**
* @notice Deposits into a user's committed balance, thereby bypassing the open draw.
* @param self The DrawManager state
* @param _addr The address of the user for whom to deposit
* @param _amount The amount to deposit
*/
function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr];
// if they have a committed balance
if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) {
uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId);
drawSet(self, firstDrawIndex, firstAmount.add(_amount), _addr);
} else { // they must not have any committed balance
self.usersSecondDrawIndex[_addr] = firstDrawIndex;
self.usersFirstDrawIndex[_addr] = self.openDrawIndex.sub(1);
drawSet(self, self.usersFirstDrawIndex[_addr], _amount, _addr);
}
}
/**
* @notice Withdraws a user's committed and open draws.
* @param self The DrawManager state
* @param _addr The address whose balance to withdraw
*/
function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) {
uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr];
uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr];
if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS
drawSet(self, firstDrawIndex, 0, _addr);
delete self.usersFirstDrawIndex[_addr];
}
if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS
drawSet(self, secondDrawIndex, 0, _addr);
delete self.usersSecondDrawIndex[_addr];
}
}
function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId);
require(_amount <= openTotal, "DrawMan/exceeds-open");
uint256 remaining = openTotal.sub(_amount);
drawSet(self, self.openDrawIndex, remaining, _addr);
}
/**
* @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available.
* @param self The DrawManager state
* @param _addr The user to withdraw from
* @param _amount The amount to withdraw.
*/
function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr];
uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr];
uint256 firstAmount = 0;
uint256 secondAmount = 0;
uint256 total = 0;
if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) {
secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId);
total = total.add(secondAmount);
}
if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) {
firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId);
total = total.add(firstAmount);
}
require(_amount <= total, "Pool/exceed");
uint256 remaining = total.sub(_amount);
// if there was a second amount that needs to be updated
if (block.timestamp > firstAmount) { //injected CONTRACT AFFECTED BY MINERS
uint256 secondRemaining = remaining.sub(firstAmount);
drawSet(self, secondDrawIndex, secondRemaining, _addr);
} else if (block.gaslimit > 0) { // else delete the second amount if it exists //injected CONTRACT AFFECTED BY MINERS
delete self.usersSecondDrawIndex[_addr];
drawSet(self, secondDrawIndex, 0, _addr);
}
// if the first amount needs to be destroyed
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
delete self.usersFirstDrawIndex[_addr];
drawSet(self, firstDrawIndex, 0, _addr);
} else if (block.number < firstAmount) { //injected CONTRACT AFFECTED BY MINERS
drawSet(self, firstDrawIndex, remaining, _addr);
}
}
/**
* @notice Returns the total balance for an address, including committed balances and the open balance.
*/
function balanceOf(State storage drawState, address _addr) public view returns (uint256) {
return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr));
}
/**
* @notice Returns the total committed balance for an address.
* @param self The DrawManager state
* @param _addr The address whose committed balance should be returned
* @return The total committed balance
*/
function committedBalanceOf(State storage self, address _addr) public view returns (uint256) {
uint256 balance = 0;
uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr];
uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr];
if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) {
balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), bytes32(uint256(_addr))));
}
if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) {
balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), bytes32(uint256(_addr))));
}
return balance;
}
/**
* @notice Returns the open balance for an address
* @param self The DrawManager state
* @param _addr The address whose open balance should be returned
* @return The open balance
*/
function openBalanceOf(State storage self, address _addr) public view returns (uint256) {
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
return 0;
} else {
return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr)));
}
}
/**
* @notice Returns the open Draw balance for the DrawManager
* @param self The DrawManager state
* @return The open draw total balance
*/
function openSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(bytes32(self.openDrawIndex));
}
/**
* @notice Returns the committed balance for the DrawManager
* @param self The DrawManager state
* @return The total committed balance
*/
function committedSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(TREE_OF_DRAWS);
}
/**
* @notice Updates the Draw balance for an address.
* @param self The DrawManager state
* @param _drawIndex The Draw index
* @param _amount The new balance
* @param _addr The address whose balance should be updated
*/
function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal {
bytes32 drawId = bytes32(_drawIndex);
bytes32 userId = bytes32(uint256(_addr));
uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId);
if (block.gaslimit != _amount) { //injected CONTRACT AFFECTED BY MINERS
// If the amount has changed
// Update the Draw's balance for that address
self.sortitionSumTrees.set(drawId, _amount, userId);
// if the draw is committed
if (block.timestamp != self.openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS
// Get the new draw total
uint256 newDrawTotal = self.sortitionSumTrees.total(drawId);
// update the draw in the committed tree
self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId);
}
}
}
/**
* @notice Selects an address by indexing into the committed tokens using the passed token
* @param self The DrawManager state
* @param _token The token index to select
* @return The selected address
*/
function draw(State storage self, uint256 _token) public view returns (address) {
// If there is no one to select, just return the zero address
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
return address(0);
}
require(_token < committedSupply(self), "Pool/ineligible");
uint256 drawIndex = uint256(self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token));
uint256 drawSupply = self.sortitionSumTrees.total(bytes32(drawIndex));
uint256 drawToken = _token % drawSupply;
return address(uint256(self.sortitionSumTrees.draw(bytes32(drawIndex), drawToken)));
}
/**
* @notice Selects an address using the entropy as an index into the committed tokens
* The entropy is passed into the UniformRandomNumber library to remove modulo bias.
* @param self The DrawManager state
* @param _entropy The random entropy to use
* @return The selected address
*/
function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) {
return draw(self, UniformRandomNumber.uniform(uint256(_entropy), committedSupply(self)));
}
modifier requireOpenDraw(State storage self) {
require(self.openDrawIndex > 0, "Pool/no-open");
_;
}
modifier requireCommittedDraw(State storage self) {
require(self.openDrawIndex > 1, "Pool/no-commit");
_;
}
modifier onlyNonZero(address _addr) {
require(_addr != address(0), "Pool/not-zero");
_;
}
}
/**
* @title FixidityLib
* @author Gadi Guy, Alberto Cuesta Canada
* @notice This library provides fixed point arithmetic with protection against
* overflow.
* All operations are done with int256 and the operands must have been created
* with any of the newFrom* functions, which shift the comma digits() to the
* right and check for limits.
* When using this library be sure of using maxNewFixed() as the upper limit for
* creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and
* maxFixedAdd() if you want to be certain that those operations don't
* overflow.
*/
library FixidityLib {
/**
* @notice Number of positions that the comma is shifted to the right.
*/
function digits() public pure returns(uint8) {
return 24;
}
/**
* @notice This is 1 in the fixed point units used in this library.
* @dev Test fixed1() equals 10^digits()
* Hardcoded to 24 digits.
*/
function fixed1() public pure returns(int256) {
return 1000000000000000000000000;
}
/**
* @notice The amount of decimals lost on each multiplication operand.
* @dev Test mulPrecision() equals sqrt(fixed1)
* Hardcoded to 24 digits.
*/
function mulPrecision() public pure returns(int256) {
return 1000000000000;
}
/**
* @notice Maximum value that can be represented in an int256
* @dev Test maxInt256() equals 2^255 -1
*/
function maxInt256() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282019728792003956564819967;
}
/**
* @notice Minimum value that can be represented in an int256
* @dev Test minInt256 equals (2^255) * (-1)
*/
function minInt256() public pure returns(int256) {
return -57896044618658097711785492504343953926634992332820282019728792003956564819968;
}
/**
* @notice Maximum value that can be converted to fixed point. Optimize for
* @dev deployment.
* Test maxNewFixed() equals maxInt256() / fixed1()
* Hardcoded to 24 digits.
*/
function maxNewFixed() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Minimum value that can be converted to fixed point. Optimize for
* deployment.
* @dev Test minNewFixed() equals -(maxInt256()) / fixed1()
* Hardcoded to 24 digits.
*/
function minNewFixed() public pure returns(int256) {
return -57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Maximum value that can be safely used as an addition operator.
* @dev Test maxFixedAdd() equals maxInt256()-1 / 2
* Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd()
* Test add(maxFixedAdd()+1,maxFixedAdd()) throws
* Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd()
* Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws
*/
function maxFixedAdd() public pure returns(int256) {
return 28948022309329048855892746252171976963317496166410141009864396001978282409983;
}
/**
* @notice Maximum negative value that can be safely in a subtraction.
* @dev Test maxFixedSub() equals minInt256() / 2
*/
function maxFixedSub() public pure returns(int256) {
return -28948022309329048855892746252171976963317496166410141009864396001978282409984;
}
/**
* @notice Maximum value that can be safely used as a multiplication operator.
* @dev Calculated as sqrt(maxInt256()*fixed1()).
* Be careful with your sqrt() implementation. I couldn't find a calculator
* that would give the exact square root of maxInt256*fixed1 so this number
* is below the real number by no more than 3*10**28. It is safe to use as
* a limit for your multiplications, although powers of two of numbers over
* this value might still work.
* Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul()
* Test multiply(maxFixedMul(),maxFixedMul()+1) throws
* Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul()
* Test multiply(-maxFixedMul(),maxFixedMul()+1) throws
* Hardcoded to 24 digits.
*/
function maxFixedMul() public pure returns(int256) {
return 240615969168004498257251713877715648331380787511296;
}
/**
* @notice Maximum value that can be safely used as a dividend.
* @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256().
* Test maxFixedDiv() equals maxInt256()/fixed1()
* Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits())
* Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws
* Hardcoded to 24 digits.
*/
function maxFixedDiv() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Maximum value that can be safely used as a divisor.
* @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2)
* Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1()
* Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws
* Hardcoded to 24 digits.
*/
function maxFixedDivisor() public pure returns(int256) {
return 1000000000000000000000000000000000000000000000000;
}
/**
* @notice Converts an int256 to fixed point units, equivalent to multiplying
* by 10^digits().
* @dev Test newFixed(0) returns 0
* Test newFixed(1) returns fixed1()
* Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1()
* Test newFixed(maxNewFixed()+1) fails
*/
function newFixed(int256 x)
public
pure
returns (int256)
{
require(x <= maxNewFixed());
require(x >= minNewFixed());
return x * fixed1();
}
/**
* @notice Converts an int256 in the fixed point representation of this
* library to a non decimal. All decimal digits will be truncated.
*/
function fromFixed(int256 x)
public
pure
returns (int256)
{
return x / fixed1();
}
/**
* @notice Converts an int256 which is already in some fixed point
* representation to a different fixed precision representation.
* Both the origin and destination precisions must be 38 or less digits.
* Origin values with a precision higher than the destination precision
* will be truncated accordingly.
* @dev
* Test convertFixed(1,0,0) returns 1;
* Test convertFixed(1,1,1) returns 1;
* Test convertFixed(1,1,0) returns 0;
* Test convertFixed(1,0,1) returns 10;
* Test convertFixed(10,1,0) returns 1;
* Test convertFixed(10,0,1) returns 100;
* Test convertFixed(100,1,0) returns 10;
* Test convertFixed(100,0,1) returns 1000;
* Test convertFixed(1000,2,0) returns 10;
* Test convertFixed(1000,0,2) returns 100000;
* Test convertFixed(1000,2,1) returns 100;
* Test convertFixed(1000,1,2) returns 10000;
* Test convertFixed(maxInt256,1,0) returns maxInt256/10;
* Test convertFixed(maxInt256,0,1) throws
* Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38);
* Test convertFixed(1,0,38) returns 10**38;
* Test convertFixed(maxInt256,39,0) throws
* Test convertFixed(1,0,39) throws
*/
function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits)
public
pure
returns (int256)
{
require(_originDigits <= 38 && _destinationDigits <= 38);
uint8 decimalDifference;
if ( _originDigits > _destinationDigits ){
decimalDifference = _originDigits - _destinationDigits;
return x/(uint128(10)**uint128(decimalDifference));
}
else if ( _originDigits < _destinationDigits ){
decimalDifference = _destinationDigits - _originDigits;
// Cast uint8 -> uint128 is safe
// Exponentiation is safe:
// _originDigits and _destinationDigits limited to 38 or less
// decimalDifference = abs(_destinationDigits - _originDigits)
// decimalDifference < 38
// 10**38 < 2**128-1
require(x <= maxInt256()/uint128(10)**uint128(decimalDifference));
require(x >= minInt256()/uint128(10)**uint128(decimalDifference));
return x*(uint128(10)**uint128(decimalDifference));
}
// _originDigits == digits())
return x;
}
/**
* @notice Converts an int256 which is already in some fixed point
* representation to that of this library. The _originDigits parameter is the
* precision of x. Values with a precision higher than FixidityLib.digits()
* will be truncated accordingly.
*/
function newFixed(int256 x, uint8 _originDigits)
public
pure
returns (int256)
{
return convertFixed(x, _originDigits, digits());
}
/**
* @notice Converts an int256 in the fixed point representation of this
* library to a different representation. The _destinationDigits parameter is the
* precision of the output x. Values with a precision below than
* FixidityLib.digits() will be truncated accordingly.
*/
function fromFixed(int256 x, uint8 _destinationDigits)
public
pure
returns (int256)
{
return convertFixed(x, digits(), _destinationDigits);
}
/**
* @notice Converts two int256 representing a fraction to fixed point units,
* equivalent to multiplying dividend and divisor by 10^digits().
* @dev
* Test newFixedFraction(maxFixedDiv()+1,1) fails
* Test newFixedFraction(1,maxFixedDiv()+1) fails
* Test newFixedFraction(1,0) fails
* Test newFixedFraction(0,1) returns 0
* Test newFixedFraction(1,1) returns fixed1()
* Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1()
* Test newFixedFraction(1,fixed1()) returns 1
* Test newFixedFraction(1,fixed1()-1) returns 0
*/
function newFixedFraction(
int256 numerator,
int256 denominator
)
public
pure
returns (int256)
{
require(numerator <= maxNewFixed());
require(denominator <= maxNewFixed());
require(denominator != 0);
int256 convertedNumerator = newFixed(numerator);
int256 convertedDenominator = newFixed(denominator);
return divide(convertedNumerator, convertedDenominator);
}
/**
* @notice Returns the integer part of a fixed point number.
* @dev
* Test integer(0) returns 0
* Test integer(fixed1()) returns fixed1()
* Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
* Test integer(-fixed1()) returns -fixed1()
* Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1()
*/
function integer(int256 x) public pure returns (int256) {
return (x / fixed1()) * fixed1(); // Can't overflow
}
/**
* @notice Returns the fractional part of a fixed point number.
* In the case of a negative number the fractional is also negative.
* @dev
* Test fractional(0) returns 0
* Test fractional(fixed1()) returns 0
* Test fractional(fixed1()-1) returns 10^24-1
* Test fractional(-fixed1()) returns 0
* Test fractional(-fixed1()+1) returns -10^24-1
*/
function fractional(int256 x) public pure returns (int256) {
return x - (x / fixed1()) * fixed1(); // Can't overflow
}
/**
* @notice Converts to positive if negative.
* Due to int256 having one more negative number than positive numbers
* abs(minInt256) reverts.
* @dev
* Test abs(0) returns 0
* Test abs(fixed1()) returns -fixed1()
* Test abs(-fixed1()) returns fixed1()
* Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
* Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1()
*/
function abs(int256 x) public pure returns (int256) {
if (x >= 0) {
return x;
} else {
int256 result = -x;
assert (result > 0);
return result;
}
}
/**
* @notice x+y. If any operator is higher than maxFixedAdd() it
* might overflow.
* In solidity maxInt256 + 1 = minInt256 and viceversa.
* @dev
* Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1
* Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails
* Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256()
* Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails
* Test add(maxInt256(),maxInt256()) fails
* Test add(minInt256(),minInt256()) fails
*/
function add(int256 x, int256 y) public pure returns (int256) {
int256 z = x + y;
if (x > 0 && y > 0) assert(z > x && z > y);
if (x < 0 && y < 0) assert(z < x && z < y);
return z;
}
/**
* @notice x-y. You can use add(x,-y) instead.
* @dev Tests covered by add(x,y)
*/
function subtract(int256 x, int256 y) public pure returns (int256) {
return add(x,-y);
}
/**
* @notice x*y. If any of the operators is higher than maxFixedMul() it
* might overflow.
* @dev
* Test multiply(0,0) returns 0
* Test multiply(maxFixedMul(),0) returns 0
* Test multiply(0,maxFixedMul()) returns 0
* Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul()
* Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul()
* Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5)
* Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision())
* Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1)
* Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits
* Test multiply(maxFixedMul()+1,maxFixedMul()) fails
* Test multiply(maxFixedMul(),maxFixedMul()+1) fails
*/
function multiply(int256 x, int256 y) public pure returns (int256) {
if (x == 0 || y == 0) return 0;
if (y == fixed1()) return x;
if (x == fixed1()) return y;
// Separate into integer and fractional parts
// x = x1 + x2, y = y1 + y2
int256 x1 = integer(x) / fixed1();
int256 x2 = fractional(x);
int256 y1 = integer(y) / fixed1();
int256 y2 = fractional(y);
// (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2)
int256 x1y1 = x1 * y1;
if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1
// x1y1 needs to be multiplied back by fixed1
// solium-disable-next-line mixedcase
int256 fixed_x1y1 = x1y1 * fixed1();
if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1
x1y1 = fixed_x1y1;
int256 x2y1 = x2 * y1;
if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1
int256 x1y2 = x1 * y2;
if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2
x2 = x2 / mulPrecision();
y2 = y2 / mulPrecision();
int256 x2y2 = x2 * y2;
if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2
// result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1();
int256 result = x1y1;
result = add(result, x2y1); // Add checks for overflow
result = add(result, x1y2); // Add checks for overflow
result = add(result, x2y2); // Add checks for overflow
return result;
}
/**
* @notice 1/x
* @dev
* Test reciprocal(0) fails
* Test reciprocal(fixed1()) returns fixed1()
* Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated
* Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated
*/
function reciprocal(int256 x) public pure returns (int256) {
require(x != 0);
return (fixed1()*fixed1()) / x; // Can't overflow
}
/**
* @notice x/y. If the dividend is higher than maxFixedDiv() it
* might overflow. You can use multiply(x,reciprocal(y)) instead.
* There is a loss of precision on division for the lower mulPrecision() decimals.
* @dev
* Test divide(fixed1(),0) fails
* Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits())
* Test divide(maxFixedDiv()+1,1) throws
* Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1()
*/
function divide(int256 x, int256 y) public pure returns (int256) {
if (y == fixed1()) return x;
require(y != 0);
require(y <= maxFixedDivisor());
return multiply(x, reciprocal(y));
}
}
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destoys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
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.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @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");
}
}
/**
* @dev Implementation of the {IERC777} interface.
*
* Largely taken from the OpenZeppelin ERC777 contract.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*
* It is important to note that no Mint events are emitted. Tokens are minted in batches
* by a state change in a tree data structure, so emitting a Mint event for each user
* is not possible.
*
*/
contract PoolToken is Initializable, IERC20, IERC777 {
using SafeMath for uint256;
using Address for address;
/**
* Event emitted when a user or operator redeems tokens
*/
event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// keccak256("ERC777Token")
bytes32 constant internal TOKENS_INTERFACE_HASH =
0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054;
// keccak256("ERC20Token")
bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH =
0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a;
string internal _name;
string internal _symbol;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] internal _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) internal _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) internal _operators;
mapping(address => mapping(address => bool)) internal _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) internal _allowances;
BasePool internal _pool;
function init (
string memory name,
string memory symbol,
address[] memory defaultOperators,
BasePool pool
) public initializer {
require(bytes(name).length != 0, "PoolToken/name");
require(bytes(symbol).length != 0, "PoolToken/symbol");
require(address(pool) != address(0), "PoolToken/pool-zero");
_name = name;
_symbol = symbol;
_pool = pool;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this));
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this));
}
function pool() public view returns (address) {
return address(_pool);
}
function poolRedeem(address from, uint256 amount) external onlyPool {
_callTokensToSend(from, from, address(0), amount, '', '');
emit Redeemed(from, from, amount, '', '');
emit Transfer(from, address(0), amount);
}
/**
* @dev See {IERC777-name}.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20Detailed-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _pool.committedSupply();
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address _addr) external view returns (uint256) {
return _pool.committedBalanceOf(_addr);
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external {
_send(msg.sender, msg.sender, recipient, amount, data, "");
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "PoolToken/transfer-zero");
address from = msg.sender;
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev Allows a user to withdraw their tokens as the underlying asset.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function redeem(uint256 amount, bytes calldata data) external {
_redeem(msg.sender, msg.sender, amount, data, "");
}
/**
* @dev See {IERC777-burn}. Not currently implemented.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function burn(uint256, bytes calldata) external {
revert("PoolToken/no-support");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external {
require(msg.sender != operator, "PoolToken/auth-self");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[msg.sender][operator];
} else {
_operators[msg.sender][operator] = true;
}
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external {
require(operator != msg.sender, "PoolToken/revoke-self");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[msg.sender][operator] = true;
} else {
delete _operators[msg.sender][operator];
}
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
)
external
{
require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator");
_send(msg.sender, sender, recipient, amount, data, operatorData);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Currently not supported
*/
function operatorBurn(address, uint256, bytes calldata, bytes calldata) external {
revert("PoolToken/no-support");
}
/**
* @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user.
*
* Emits {Redeemed} and {Transfer} events.
*/
function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(msg.sender, account), "PoolToken/not-operator");
_redeem(msg.sender, account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external returns (bool) {
address holder = msg.sender;
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {Transfer} and {Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "PoolToken/to-zero");
require(holder != address(0), "PoolToken/from-zero");
address spender = msg.sender;
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* Called by the associated Pool to emit `Mint` events.
* @param amount The amount that was minted
*/
function poolMint(uint256 amount) external onlyPool {
_mintEvents(address(_pool), address(_pool), amount, '', '');
}
/**
* Emits {Minted} and {IERC20-Transfer} events.
*/
function _mintEvents(
address operator,
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _send(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
require(to != address(0), "PoolToken/to-zero");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, true);
}
/**
* @dev Redeems tokens for the underlying asset.
* @param operator address operator requesting the operation
* @param from address token holder address
* @param amount uint256 amount of tokens to redeem
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _redeem(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_pool.withdrawCommittedDeposit(from, amount);
emit Redeemed(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_pool.moveCommitted(from, to, amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
function _approve(address holder, address spender, uint256 value) private {
require(spender != address(0), "PoolToken/from-zero");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal notLocked
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck Whether the recipient, when a contract, *must* have a IERC777Recipient implementor
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "PoolToken/no-recip-inter");
}
}
modifier onlyPool() {
require(msg.sender == address(_pool), "PoolToken/only-pool");
_;
}
modifier notLocked() {
require(!_pool.isLocked(), "PoolToken/is-locked");
_;
}
}
/**
* @title The Pool contract
* @author Brendan Asselstine
* @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws.
* Funds are immediately deposited and withdrawn from the Compound cToken contract.
* Draws go through three stages: open, committed and rewarded in that order.
* Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance.
* When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated.
* When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being
* proportional to their committed balance vs the total committed balance of all users.
*
*
* With the above in mind, there is always an open draw and possibly a committed draw. The progression is:
*
* Step 1: Draw 1 Open
* Step 2: Draw 2 Open | Draw 1 Committed
* Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded
* Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded
* Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded
* Step X: ...
*/
contract BasePool is Initializable, ReentrancyGuard {
using DrawManager for DrawManager.State;
using SafeMath for uint256;
using Roles for Roles.Role;
using Blocklock for Blocklock.State;
bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1));
uint256 internal constant DEFAULT_LOCK_DURATION = 40;
uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80;
/**
* Emitted when a user deposits into the Pool.
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event Deposited(address indexed sender, uint256 amount);
/**
* Emitted when a user deposits into the Pool and the deposit is immediately committed
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event DepositedAndCommitted(address indexed sender, uint256 amount);
/**
* Emitted when Sponsors have deposited into the Pool
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event SponsorshipDeposited(address indexed sender, uint256 amount);
/**
* Emitted when an admin has been added to the Pool.
* @param admin The admin that was added
*/
event AdminAdded(address indexed admin);
/**
* Emitted when an admin has been removed from the Pool.
* @param admin The admin that was removed
*/
event AdminRemoved(address indexed admin);
/**
* Emitted when a user withdraws from the pool.
* @param sender The user that is withdrawing from the pool
* @param amount The amount that the user withdrew
*/
event Withdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws their sponsorship and fees from the pool.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws from their open deposit.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event OpenDepositWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws from their committed deposit.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event CommittedDepositWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when an address collects a fee
* @param sender The address collecting the fee
* @param amount The fee amount
* @param drawId The draw from which the fee was awarded
*/
event FeeCollected(address indexed sender, uint256 amount, uint256 drawId);
/**
* Emitted when a new draw is opened for deposit.
* @param drawId The draw id
* @param feeBeneficiary The fee beneficiary for this draw
* @param secretHash The committed secret hash
* @param feeFraction The fee fraction of the winnings to be given to the beneficiary
*/
event Opened(
uint256 indexed drawId,
address indexed feeBeneficiary,
bytes32 secretHash,
uint256 feeFraction
);
/**
* Emitted when a draw is committed.
* @param drawId The draw id
*/
event Committed(
uint256 indexed drawId
);
/**
* Emitted when a draw is rewarded.
* @param drawId The draw id
* @param winner The address of the winner
* @param entropy The entropy used to select the winner
* @param winnings The net winnings given to the winner
* @param fee The fee being given to the draw beneficiary
*/
event Rewarded(
uint256 indexed drawId,
address indexed winner,
bytes32 entropy,
uint256 winnings,
uint256 fee
);
/**
* Emitted when the fee fraction is changed. Takes effect on the next draw.
* @param feeFraction The next fee fraction encoded as a fixed point 18 decimal
*/
event NextFeeFractionChanged(uint256 feeFraction);
/**
* Emitted when the next fee beneficiary changes. Takes effect on the next draw.
* @param feeBeneficiary The next fee beneficiary
*/
event NextFeeBeneficiaryChanged(address indexed feeBeneficiary);
/**
* Emitted when an admin pauses the contract
*/
event Paused(address indexed sender);
/**
* Emitted when an admin unpauses the contract
*/
event Unpaused(address indexed sender);
/**
* Emitted when the draw is rolled over in the event that the secret is forgotten.
*/
event RolledOver(uint256 indexed drawId);
struct Draw {
uint256 feeFraction; //fixed point 18
address feeBeneficiary;
uint256 openedBlock;
bytes32 secretHash;
bytes32 entropy;
address winner;
uint256 netWinnings;
uint256 fee;
}
/**
* The Compound cToken that this Pool is bound to.
*/
ICErc20 public cToken;
/**
* The fee beneficiary to use for subsequent Draws.
*/
address public nextFeeBeneficiary;
/**
* The fee fraction to use for subsequent Draws.
*/
uint256 public nextFeeFraction;
/**
* The total of all balances
*/
uint256 public accountedBalance;
/**
* The total deposits and winnings for each user.
*/
mapping (address => uint256) balances;
/**
* A mapping of draw ids to Draw structures
*/
mapping(uint256 => Draw) draws;
/**
* A structure that is used to manage the user's odds of winning.
*/
DrawManager.State drawState;
/**
* A structure containing the administrators
*/
Roles.Role admins;
/**
* Whether the contract is paused
*/
bool public paused;
Blocklock.State blocklock;
PoolToken public poolToken;
/**
* @notice Initializes a new Pool contract.
* @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries.
* @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens.
* @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number.
* @param _feeBeneficiary The address that will receive the fee fraction
*/
function init (
address _owner,
address _cToken,
uint256 _feeFraction,
address _feeBeneficiary,
uint256 _lockDuration,
uint256 _cooldownDuration
) public initializer {
require(_owner != address(0), "Pool/owner-zero");
require(_cToken != address(0), "Pool/ctoken-zero");
cToken = ICErc20(_cToken);
_addAdmin(_owner);
_setNextFeeFraction(_feeFraction);
_setNextFeeBeneficiary(_feeBeneficiary);
initBlocklock(_lockDuration, _cooldownDuration);
}
function setPoolToken(PoolToken _poolToken) external onlyAdmin {
require(address(poolToken) == address(0), "Pool/token-was-set");
require(_poolToken.pool() == address(this), "Pool/token-mismatch");
poolToken = _poolToken;
}
function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal {
blocklock.setLockDuration(_lockDuration);
blocklock.setCooldownDuration(_cooldownDuration);
}
/**
* @notice Opens a new Draw.
* @param _secretHash The secret hash to commit to the Draw.
*/
function open(bytes32 _secretHash) internal {
drawState.openNextDraw();
draws[drawState.openDrawIndex] = Draw(
nextFeeFraction,
nextFeeBeneficiary,
block.number,
_secretHash,
bytes32(0),
address(0),
uint256(0),
uint256(0)
);
emit Opened(
drawState.openDrawIndex,
nextFeeBeneficiary,
_secretHash,
nextFeeFraction
);
}
/**
* @notice Commits the current draw.
*/
function emitCommitted() internal {
uint256 drawId = currentOpenDrawId();
emit Committed(drawId);
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
poolToken.poolMint(openSupply());
}
}
/**
* @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice:
* the first after Pool contract creation and the second immediately after.
* Can only be called by an admin.
* May fire the Committed event, and always fires the Open event.
* @param nextSecretHash The secret hash to use to open a new Draw
*/
function openNextDraw(bytes32 nextSecretHash) public onlyAdmin {
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward");
}
if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS
emitCommitted();
}
open(nextSecretHash);
}
/**
* @notice Ignores the current draw, and opens the next draw.
* @dev This function will be removed once the winner selection has been decentralized.
* @param nextSecretHash The hash to commit for the next draw
*/
function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin {
rollover();
openNextDraw(nextSecretHash);
}
/**
* @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash.
* Can only be called by an admin.
* Fires the Rewarded event, the Committed event, and the Open event.
* @param nextSecretHash The secret hash to use to open a new Draw
* @param lastSecret The secret to reveal to reward the current committed Draw.
* @param _salt The salt that was combined with the revealed secret to use as the hash. Expects secretHash == keccak256(abi.encodePacked(_secret, _salt))
*/
function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin {
reward(lastSecret, _salt);
openNextDraw(nextSecretHash);
}
/**
* @notice Rewards the winner for the current committed Draw using the passed secret.
* The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance.
* A winner is calculated using the revealed secret.
* If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings.
* The draw beneficiary's balance is updated with the fee.
* The accounted balance is updated to include the fee and, if there was a winner, the net winnings.
* Fires the Rewarded event.
* @param _secret The secret to reveal for the current committed Draw
* @param _salt The salt that was combined with the revealed secret to use as the hash. Expects secretHash == keccak256(abi.encodePacked(_secret, _salt))
*/
function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant {
blocklock.unlock(block.number);
// require that there is a committed draw
// require that the committed draw has not been rewarded
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret");
// derive entropy from the revealed secret
bytes32 entropy = keccak256(abi.encodePacked(_secret));
// Select the winner using the hash as entropy
address winningAddress = calculateWinner(entropy);
// Calculate the gross winnings
uint256 underlyingBalance = balance();
uint256 grossWinnings = underlyingBalance.sub(accountedBalance);
// Calculate the beneficiary fee
uint256 fee = calculateFee(draw.feeFraction, grossWinnings);
// Update balance of the beneficiary
balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee);
// Calculate the net winnings
uint256 netWinnings = grossWinnings.sub(fee);
draw.winner = winningAddress;
draw.netWinnings = netWinnings;
draw.fee = fee;
draw.entropy = entropy;
// If there is a winner who is to receive non-zero winnings
if (winningAddress != address(0) && netWinnings != 0) {
// Updated the accounted total
accountedBalance = underlyingBalance;
awardWinnings(winningAddress, netWinnings);
} else {
// Only account for the fee
accountedBalance = accountedBalance.add(fee);
}
emit Rewarded(
drawId,
winningAddress,
entropy,
netWinnings,
fee
);
emit FeeCollected(draw.feeBeneficiary, fee, drawId);
}
function awardWinnings(address winner, uint256 amount) internal {
// Update balance of the winner
balances[winner] = balances[winner].add(amount);
// Enter their winnings into the open draw
drawState.deposit(winner, amount);
}
/**
* @notice A function that skips the reward for the committed draw id.
* @dev This function will be removed once the entropy is decentralized.
*/
function rollover() public onlyAdmin requireCommittedNoReward {
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER;
emit RolledOver(
drawId
);
emit Rewarded(
drawId,
address(0),
ROLLED_OVER_ENTROPY_MAGIC_NUMBER,
0,
0
);
}
/**
* @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings.
* @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number.
* @param _grossWinnings The gross winnings to take a fraction of.
*/
function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) {
int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings));
int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18)));
return uint256(FixidityLib.fromFixed(feeFixed));
}
/**
* @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken.
* Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time.
* The deposit will immediately be added to Compound and the interest will contribute to the next draw.
* @param _amount The amount of the token underlying the cToken to deposit.
*/
function depositSponsorship(uint256 _amount) public unlessPaused nonReentrant {
// Transfer the tokens into this contract
require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail");
// Deposit the sponsorship amount
_depositSponsorshipFrom(msg.sender, _amount);
}
/**
* @notice Deposits the token balance for this contract as a sponsorship.
* If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship.
*/
function transferBalanceToSponsorship() public unlessPaused {
// Deposit the sponsorship amount
_depositSponsorshipFrom(address(this), token().balanceOf(address(this)));
}
/**
* @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken.
* Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning
* proportional to the total committed balance of all users.
* @param _amount The amount of the token underlying the cToken to deposit.
*/
function depositPool(uint256 _amount) public requireOpenDraw unlessPaused nonReentrant {
// Transfer the tokens into this contract
require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail");
// Deposit the funds
_depositPoolFrom(msg.sender, _amount);
}
function _depositSponsorshipFrom(address _spender, uint256 _amount) internal {
// Deposit the funds
_depositFrom(_spender, _amount);
emit SponsorshipDeposited(_spender, _amount);
}
function _depositPoolFrom(address _spender, uint256 _amount) internal {
// Update the user's eligibility
drawState.deposit(_spender, _amount);
_depositFrom(_spender, _amount);
emit Deposited(_spender, _amount);
}
function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked {
// Update the user's eligibility
drawState.depositCommitted(_spender, _amount);
_depositFrom(_spender, _amount);
emit DepositedAndCommitted(_spender, _amount);
}
function _depositFrom(address _spender, uint256 _amount) internal {
// Update the user's balance
balances[_spender] = balances[_spender].add(_amount);
// Update the total of this contract
accountedBalance = accountedBalance.add(_amount);
// Deposit into Compound
require(token().approve(address(cToken), _amount), "Pool/approve");
require(cToken.mint(_amount) == 0, "Pool/supply");
}
/**
* @notice Withdraw the sender's entire balance back to them.
*/
function withdraw() public nonReentrant notLocked {
uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender);
uint256 openBalance = drawState.openBalanceOf(msg.sender);
uint256 committedBalance = drawState.committedBalanceOf(msg.sender);
uint balance = balances[msg.sender];
// Update their chances of winning
drawState.withdraw(msg.sender);
_withdraw(msg.sender, balance);
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
poolToken.poolRedeem(msg.sender, committedBalance);
}
emit SponsorshipAndFeesWithdrawn(msg.sender, sponsorshipAndFees);
emit OpenDepositWithdrawn(msg.sender, openBalance);
emit CommittedDepositWithdrawn(msg.sender, committedBalance);
emit Withdrawn(msg.sender, balance);
}
/**
* Withdraws only from the sender's sponsorship and fee balances
* @param _amount The amount to withdraw
*/
function withdrawSponsorshipAndFee(uint256 _amount) public {
uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender);
require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee");
_withdraw(msg.sender, _amount);
emit SponsorshipAndFeesWithdrawn(msg.sender, _amount);
}
/**
* Returns the total balance of the users sponsorship and fees
* @param _sender The user whose balance should be returned
*/
function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) {
return balances[_sender] - drawState.balanceOf(_sender);
}
/**
* Withdraws from the users open deposits
* @param _amount The amount to withdraw
*/
function withdrawOpenDeposit(uint256 _amount) public {
drawState.withdrawOpen(msg.sender, _amount);
_withdraw(msg.sender, _amount);
emit OpenDepositWithdrawn(msg.sender, _amount);
}
/**
* Withdraws from the users committed deposits
* @param _amount The amount to withdraw
*/
function withdrawCommittedDeposit(uint256 _amount) external notLocked returns (bool) {
_withdrawCommittedDepositAndEmit(msg.sender, _amount);
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
poolToken.poolRedeem(msg.sender, _amount);
}
return true;
}
/**
* Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token.
* @param _from The user to withdraw from
* @param _amount The amount to withdraw
*/
function withdrawCommittedDeposit(
address _from,
uint256 _amount
) external onlyToken notLocked returns (bool) {
return _withdrawCommittedDepositAndEmit(_from, _amount);
}
/**
* A function that withdraws committed deposits for a user and emit the corresponding events.
* @param _from User to withdraw for
* @param _amount The amount to withdraw
*/
function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) {
drawState.withdrawCommitted(_from, _amount);
_withdraw(_from, _amount);
emit CommittedDepositWithdrawn(_from, _amount);
return true;
}
/**
* Allows the associated PoolToken to move committed tokens from one user to another.
*/
function moveCommitted(
address _from,
address _to,
uint256 _amount
) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) {
balances[_from] = balances[_from].sub(_amount, "move could not sub amount");
balances[_to] = balances[_to].add(_amount);
drawState.withdrawCommitted(_from, _amount);
drawState.depositCommitted(_to, _amount);
return true;
}
/**
* @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance.
*/
function _withdraw(address _sender, uint256 _amount) internal {
uint balance = balances[_sender];
require(_amount <= balance, "Pool/no-funds");
// Update the user's balance
balances[_sender] = balance.sub(_amount);
// Update the total of this contract
accountedBalance = accountedBalance.sub(_amount);
// Withdraw from Compound and transfer
require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem");
require(token().transfer(_sender, _amount), "Pool/transfer");
}
/**
* @notice Returns the id of the current open Draw.
* @return The current open Draw id
*/
function currentOpenDrawId() public view returns (uint256) {
return drawState.openDrawIndex;
}
/**
* @notice Returns the id of the current committed Draw.
* @return The current committed Draw id
*/
function currentCommittedDrawId() public view returns (uint256) {
if (block.timestamp > 1) { //injected CONTRACT AFFECTED BY MINERS
return drawState.openDrawIndex - 1;
} else {
return 0;
}
}
/**
* @notice Returns whether the current committed draw has been rewarded
* @return True if the current committed draw has been rewarded, false otherwise
*/
function currentCommittedDrawHasBeenRewarded() internal view returns (bool) {
Draw storage draw = draws[currentCommittedDrawId()];
return draw.entropy != bytes32(0);
}
/**
* @notice Gets information for a given draw.
* @param _drawId The id of the Draw to retrieve info for.
* @return Fields including:
* feeFraction: the fee fraction
* feeBeneficiary: the beneficiary of the fee
* openedBlock: The block at which the draw was opened
* secretHash: The hash of the secret committed to this draw.
*/
function getDraw(uint256 _drawId) public view returns (
uint256 feeFraction,
address feeBeneficiary,
uint256 openedBlock,
bytes32 secretHash,
bytes32 entropy,
address winner,
uint256 netWinnings,
uint256 fee
) {
Draw storage draw = draws[_drawId];
feeFraction = draw.feeFraction;
feeBeneficiary = draw.feeBeneficiary;
openedBlock = draw.openedBlock;
secretHash = draw.secretHash;
entropy = draw.entropy;
winner = draw.winner;
netWinnings = draw.netWinnings;
fee = draw.fee;
}
/**
* @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning.
* @param _addr The address of the user
* @return The total committed balance for the user
*/
function committedBalanceOf(address _addr) external view returns (uint256) {
return drawState.committedBalanceOf(_addr);
}
/**
* @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning.
* @param _addr The address of the user
* @return The total open balance for the user
*/
function openBalanceOf(address _addr) external view returns (uint256) {
return drawState.openBalanceOf(_addr);
}
/**
* @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits.
* @param _addr The address of the user to check.
* @return The users's current balance.
*/
function totalBalanceOf(address _addr) external view returns (uint256) {
return balances[_addr];
}
/**
* @notice Returns a user's total balance, including both committed Draw balance and open Draw balance.
* @param _addr The address of the user to check.
* @return The users's current balance.
*/
function balanceOf(address _addr) external view returns (uint256) {
return drawState.committedBalanceOf(_addr);
}
/**
* @notice Calculates a winner using the passed entropy for the current committed balances.
* @param _entropy The entropy to use to select the winner
* @return The winning address
*/
function calculateWinner(bytes32 _entropy) public view returns (address) {
return drawState.drawWithEntropy(_entropy);
}
/**
* @notice Returns the total committed balance. Used to compute an address's chances of winning.
* @return The total committed balance.
*/
function committedSupply() public view returns (uint256) {
return drawState.committedSupply();
}
/**
* @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw.
* @return The total open balance
*/
function openSupply() public view returns (uint256) {
return drawState.openSupply();
}
/**
* @notice Calculates the total estimated interest earned for the given number of blocks
* @param _blocks The number of block that interest accrued for
* @return The total estimated interest as a 18 point fixed decimal.
*/
function estimatedInterestRate(uint256 _blocks) public view returns (uint256) {
return supplyRatePerBlock().mul(_blocks);
}
/**
* @notice Convenience function to return the supplyRatePerBlock value from the money market contract.
* @return The cToken supply rate per block
*/
function supplyRatePerBlock() public view returns (uint256) {
return cToken.supplyRatePerBlock();
}
/**
* @notice Sets the beneficiary fee fraction for subsequent Draws.
* Fires the NextFeeFractionChanged event.
* Can only be called by an admin.
* @param _feeFraction The fee fraction to use.
* Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether).
*/
function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin {
_setNextFeeFraction(_feeFraction);
}
function _setNextFeeFraction(uint256 _feeFraction) internal {
require(_feeFraction <= 1 ether, "Pool/less-1");
nextFeeFraction = _feeFraction;
emit NextFeeFractionChanged(_feeFraction);
}
/**
* @notice Sets the fee beneficiary for subsequent Draws.
* Can only be called by admins.
* @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address.
*/
function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin {
_setNextFeeBeneficiary(_feeBeneficiary);
}
function _setNextFeeBeneficiary(address _feeBeneficiary) internal {
require(_feeBeneficiary != address(0), "Pool/not-zero");
nextFeeBeneficiary = _feeBeneficiary;
emit NextFeeBeneficiaryChanged(_feeBeneficiary);
}
/**
* @notice Adds an administrator.
* Can only be called by administrators.
* Fires the AdminAdded event.
* @param _admin The address of the admin to add
*/
function addAdmin(address _admin) public onlyAdmin {
_addAdmin(_admin);
}
/**
* @notice Checks whether a given address is an administrator.
* @param _admin The address to check
* @return True if the address is an admin, false otherwise.
*/
function isAdmin(address _admin) public view returns (bool) {
return admins.has(_admin);
}
function _addAdmin(address _admin) internal {
admins.add(_admin);
emit AdminAdded(_admin);
}
/**
* @notice Removes an administrator
* Can only be called by an admin.
* Admins cannot remove themselves. This ensures there is always one admin.
* @param _admin The address of the admin to remove
*/
function removeAdmin(address _admin) public onlyAdmin {
require(admins.has(_admin), "Pool/no-admin");
require(_admin != msg.sender, "Pool/remove-self");
admins.remove(_admin);
emit AdminRemoved(_admin);
}
modifier requireCommittedNoReward() {
require(currentCommittedDrawId() > 0, "Pool/committed");
require(!currentCommittedDrawHasBeenRewarded(), "Pool/already");
_;
}
/**
* @notice Returns the token underlying the cToken.
* @return An ERC20 token address
*/
function token() public view returns (IERC20) {
return IERC20(cToken.underlying());
}
/**
* @notice Returns the underlying balance of this contract in the cToken.
* @return The cToken underlying balance for this contract.
*/
function balance() public returns (uint256) {
return cToken.balanceOfUnderlying(address(this));
}
/**
* @notice Locks the movement of tokens (essentially the committed deposits and winnings)
* @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes.
*/
function lockTokens() public onlyAdmin {
blocklock.lock(block.number);
}
/**
* @notice Unlocks the movement of tokens (essentially the committed deposits)
*/
function unlockTokens() public onlyAdmin {
blocklock.unlock(block.number);
}
/**
* Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue
* to collect rewards, but eventually the Pool will grow smaller.
*/
function pause() public unlessPaused onlyAdmin {
paused = true;
emit Paused(msg.sender);
}
/**
* Unpauses all deposits into the contract
*/
function unpause() public whenPaused onlyAdmin {
paused = false;
emit Unpaused(msg.sender);
}
function isLocked() public view returns (bool) {
return blocklock.isLocked(block.number);
}
function lockEndAt() public view returns (uint256) {
return blocklock.lockEndAt();
}
function cooldownEndAt() public view returns (uint256) {
return blocklock.cooldownEndAt();
}
function canLock() public view returns (bool) {
return blocklock.canLock(block.number);
}
function lockDuration() public view returns (uint256) {
return blocklock.lockDuration;
}
function cooldownDuration() public view returns (uint256) {
return blocklock.cooldownDuration;
}
modifier notLocked() {
require(!blocklock.isLocked(block.number), "Pool/locked");
_;
}
modifier onlyLocked() {
require(blocklock.isLocked(block.number), "Pool/unlocked");
_;
}
modifier onlyAdmin() {
require(admins.has(msg.sender), "Pool/admin");
_;
}
modifier requireOpenDraw() {
require(currentOpenDrawId() != 0, "Pool/no-open");
_;
}
modifier whenPaused() {
require(paused, "Pool/be-paused");
_;
}
modifier unlessPaused() {
require(!paused, "Pool/not-paused");
_;
}
modifier onlyToken() {
require(msg.sender == address(poolToken), "Pool/only-token");
_;
}
modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) {
uint256 committedBalance = drawState.committedBalanceOf(_from);
require(_amount <= committedBalance, "not enough funds");
_;
}
}
contract ScdMcdMigration {
SaiTubLike public tub;
VatLike public vat;
ManagerLike public cdpManager;
JoinLike public saiJoin;
JoinLike public wethJoin;
JoinLike public daiJoin;
constructor(
address tub_, // SCD tub contract address
address cdpManager_, // MCD manager contract address
address saiJoin_, // MCD SAI collateral adapter contract address
address wethJoin_, // MCD ETH collateral adapter contract address
address daiJoin_ // MCD DAI adapter contract address
) public {
tub = SaiTubLike(tub_);
cdpManager = ManagerLike(cdpManager_);
vat = VatLike(cdpManager.vat());
saiJoin = JoinLike(saiJoin_);
wethJoin = JoinLike(wethJoin_);
daiJoin = JoinLike(daiJoin_);
require(wethJoin.gem() == tub.gem(), "non-matching-weth");
require(saiJoin.gem() == tub.sai(), "non-matching-sai");
tub.gov().approve(address(tub), uint(-1));
tub.skr().approve(address(tub), uint(-1));
tub.sai().approve(address(tub), uint(-1));
tub.sai().approve(address(saiJoin), uint(-1));
wethJoin.gem().approve(address(wethJoin), uint(-1));
daiJoin.dai().approve(address(daiJoin), uint(-1));
vat.hope(address(daiJoin));
}
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
// Function to swap SAI to DAI
// This function is to be used by users that want to get new DAI in exchange of old one (aka SAI)
// wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one)
function swapSaiToDai(
uint wad
) external {
// Get wad amount of SAI from user's wallet:
saiJoin.gem().transferFrom(msg.sender, address(this), wad);
// Join the SAI wad amount to the `vat`:
saiJoin.join(address(this), wad);
// Lock the SAI wad amount to the CDP and generate the same wad amount of DAI
vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad));
// Send DAI wad amount as a ERC20 token to the user's wallet
daiJoin.exit(msg.sender, wad);
}
// Function to swap DAI to SAI
// This function is to be used by users that want to get SAI in exchange of DAI
// wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP
function swapDaiToSai(
uint wad
) external {
// Get wad amount of DAI from user's wallet:
daiJoin.dai().transferFrom(msg.sender, address(this), wad);
// Join the DAI wad amount to the vat:
daiJoin.join(address(this), wad);
// Payback the DAI wad amount and unlocks the same value of SAI collateral
vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad));
// Send SAI wad amount as a ERC20 token to the user's wallet
saiJoin.exit(msg.sender, wad);
}
// Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage.
// In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio)
function migrate(
bytes32 cup
) external returns (uint cdp) {
// Get values
uint debtAmt = tub.tab(cup); // CDP SAI debt
uint pethAmt = tub.ink(cup); // CDP locked collateral
uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH
// Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio
// This is not actually a problem as this ilk will only be accessed by this migration contract,
// which will make sure to have the amounts balanced out at the end of the execution.
vat.frob(
bytes32(saiJoin.ilk()),
address(this),
address(this),
address(this),
-toInt(debtAmt),
0
);
saiJoin.exit(address(this), debtAmt); // SAI is exited as a token
// Shut SAI CDP and gets WETH back
tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call)
tub.exit(pethAmt); // Converts PETH to WETH
// Open future user's CDP in MCD
cdp = cdpManager.open(wethJoin.ilk(), address(this));
// Join WETH to Adapter
wethJoin.join(cdpManager.urns(cdp), ethAmt);
// Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP
(, uint rate,,,) = vat.ilks(wethJoin.ilk());
cdpManager.frob(
cdp,
toInt(ethAmt),
toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt
);
// Move DAI generated to migration contract (to recover the used funds)
cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27));
// Re-balance MCD SAI migration contract's CDP
vat.frob(
bytes32(saiJoin.ilk()),
address(this),
address(this),
address(this),
0,
-toInt(debtAmt)
);
// Set ownership of CDP to the user
cdpManager.give(cdp, msg.sender);
}
}
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
/**
* @title MCDAwarePool
* @author Brendan Asselstine [email protected]
* @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to
* detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai
* and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for
* users to encourage them to migrate to the MCD Pool.
*/
contract MCDAwarePool is BasePool, IERC777Recipient {
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// keccak256("ERC777TokensRecipient")
bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
/**
* @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts)
*/
ScdMcdMigration public scdMcdMigration;
/**
* @notice The address of the Sai Pool contract
*/
MCDAwarePool public saiPool;
/**
* @notice Initializes the contract.
* @param _owner The initial administrator of the contract
* @param _cToken The Compound cToken to bind this Pool to
* @param _feeFraction The fraction of the winnings to give to the beneficiary
* @param _feeBeneficiary The beneficiary who receives the fee
*/
function init (
address _owner,
address _cToken,
uint256 _feeFraction,
address _feeBeneficiary,
uint256 lockDuration,
uint256 cooldownDuration
) public initializer {
super.init(
_owner,
_cToken,
_feeFraction,
_feeBeneficiary,
lockDuration,
cooldownDuration
);
initRegistry();
initBlocklock(lockDuration, cooldownDuration);
}
/**
* @notice Used to initialze the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock.
*/
function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public {
initRegistry();
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
initBlocklock(lockDuration, cooldownDuration);
}
}
function initRegistry() internal {
ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin {
_initMigration(_scdMcdMigration, _saiPool);
}
function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal {
require(address(scdMcdMigration) == address(0), "Pool/init");
require(address(_scdMcdMigration) != address(0), "Pool/mig-def");
scdMcdMigration = _scdMcdMigration;
saiPool = _saiPool; // may be null
}
/**
* @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool
* and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of
* the sender. It will reject all other tokens.
*
* If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the
* open prize. This is to encourage migration.
*
* @param from The sender
* @param amount The amount they are transferring
*/
function tokensReceived(
address, // operator
address from,
address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface
uint256 amount,
bytes calldata,
bytes calldata
) external unlessPaused {
require(msg.sender == address(saiPoolToken()), "Pool/sai-only");
require(address(token()) == address(daiToken()), "Pool/not-dai");
// cash out of the Pool. This call transfers sai to this contract
saiPoolToken().redeem(amount, '');
// approve of the transfer to the migration contract
saiToken().approve(address(scdMcdMigration), amount);
// migrate the sai to dai. The contract now has dai
scdMcdMigration.swapSaiToDai(amount);
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
// now deposit the dai as tickets
_depositPoolFromCommitted(from, amount);
} else {
_depositPoolFrom(from, amount);
}
}
function saiPoolToken() internal view returns (PoolToken) {
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
return saiPool.poolToken();
} else {
return PoolToken(0);
}
}
function saiToken() public returns (GemLike) {
return scdMcdMigration.saiJoin().gem();
}
function daiToken() public returns (GemLike) {
return scdMcdMigration.daiJoin().dai();
}
} | * @notice Adds an administrator. Can only be called by administrators. Fires the AdminAdded event. @param _admin The address of the admin to add/ | function addAdmin(address _admin) public onlyAdmin {
_addAdmin(_admin);
}
| 14,091,951 | [
1,
3655,
392,
22330,
18,
4480,
1338,
506,
2566,
635,
30162,
3062,
18,
478,
2814,
326,
7807,
8602,
871,
18,
225,
389,
3666,
1021,
1758,
434,
326,
3981,
358,
527,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
527,
4446,
12,
2867,
389,
3666,
13,
1071,
1338,
4446,
288,
203,
565,
389,
1289,
4446,
24899,
3666,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: YFIRewards.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* 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
*/
pragma solidity 0.6.12;
import "@bancor/contracts-solidity/solidity/contracts/utility/Owned.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IExecutor.sol";
/**
* @title The Bancor Governance Contract
*
* Big thanks to synthetix / yearn.finance for the initial version!
*/
contract BancorGovernance is Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint32 internal constant PPM_RESOLUTION = 1000000;
struct Proposal {
uint256 id;
mapping(address => uint256) votesFor;
mapping(address => uint256) votesAgainst;
uint256 totalVotesFor;
uint256 totalVotesAgainst;
uint256 start; // start timestmp;
uint256 end; // start + voteDuration
uint256 totalAvailableVotes;
uint256 quorum;
uint256 quorumRequired;
bool open;
bool executed;
address proposer;
address executor;
string hash;
}
/**
* @notice triggered when a new proposal is created
*
* @param _id proposal id
* @param _start voting start timestamp
* @param _duration voting duration
* @param _proposer proposal creator
* @param _executor contract that will exeecute the proposal once it passes
*/
event NewProposal(
uint256 indexed _id,
uint256 _start,
uint256 _duration,
address _proposer,
address _executor
);
/**
* @notice triggered when voting on a proposal has ended
*
* @param _id proposal id
* @param _for number of votes for the proposal
* @param _against number of votes against the proposal
* @param _quorumReached true if quorum was reached, false otherwise
*/
event ProposalFinished(
uint256 indexed _id,
uint256 _for,
uint256 _against,
bool _quorumReached
);
/**
* @notice triggered when a proposal was successfully executed
*
* @param _id proposal id
* @param _executor contract that will execute the proposal once it passes
*/
event ProposalExecuted(uint256 indexed _id, address indexed _executor);
/**
* @notice triggered when a stake has been added to the contract
*
* @param _user staker address
* @param _amount staked amount
*/
event Staked(address indexed _user, uint256 _amount);
/**
* @notice triggered when a stake has been removed from the contract
*
* @param _user staker address
* @param _amount unstaked amount
*/
event Unstaked(address indexed _user, uint256 _amount);
/**
* @notice triggered when a user votes on a proposal
*
* @param _id proposal id
* @param _voter voter addrerss
* @param _vote true if the vote is for the proposal, false otherwise
* @param _weight number of votes
*/
event Vote(uint256 indexed _id, address indexed _voter, bool _vote, uint256 _weight);
/**
* @notice triggered when the quorum is updated
*
* @param _quorum new quorum
*/
event QuorumUpdated(uint256 _quorum);
/**
* @notice triggered when the minimum stake required to create a new proposal is updated
*
* @param _minimum new minimum
*/
event NewProposalMinimumUpdated(uint256 _minimum);
/**
* @notice triggered when the vote duration is updated
*
* @param _voteDuration new vote duration
*/
event VoteDurationUpdated(uint256 _voteDuration);
/**
* @notice triggered when the vote lock duration is updated
*
* @param _duration new vote lock duration
*/
event VoteLockDurationUpdated(uint256 _duration);
// PROPOSALS
// voting duration in seconds
uint256 public voteDuration = 3 days;
// vote lock in seconds
uint256 public voteLockDuration = 3 days;
// the fraction of vote lock used to lock voter to avoid rapid unstaking
uint256 public constant voteLockFraction = 10;
// minimum stake required to propose
uint256 public newProposalMinimum = 1e18;
// quorum needed for a proposal to pass, default = 20%
uint256 public quorum = 200000;
// sum of current total votes
uint256 public totalVotes;
// number of proposals
uint256 public proposalCount;
// proposals by id
mapping(uint256 => Proposal) public proposals;
// VOTES
// governance token used for votes
IERC20 public immutable govToken;
// lock duration for each voter stake by voter address
mapping(address => uint256) public voteLocks;
// number of votes for each user
mapping(address => uint256) private votes;
/**
* @notice used to initialize a new BancorGovernance contract
*
* @param _govToken token used to represents votes
*/
constructor(IERC20 _govToken) public {
require(address(_govToken) != address(0), "ERR_NO_TOKEN");
govToken = _govToken;
}
/**
* @notice allows execution by staker only
*/
modifier onlyStaker() {
require(votes[msg.sender] > 0, "ERR_NOT_STAKER");
_;
}
/**
* @notice allows execution only when the proposal exists
*
* @param _id proposal id
*/
modifier proposalExists(uint256 _id) {
Proposal memory proposal = proposals[_id];
require(proposal.start > 0 && proposal.start < block.timestamp, "ERR_INVALID_ID");
_;
}
/**
* @notice allows execution only when the proposal is still open
*
* @param _id proposal id
*/
modifier proposalOpen(uint256 _id) {
Proposal memory proposal = proposals[_id];
require(proposal.open, "ERR_NOT_OPEN");
_;
}
/**
* @notice allows execution only when the proposal with given id is open
*
* @param _id proposal id
*/
modifier proposalNotEnded(uint256 _id) {
Proposal memory proposal = proposals[_id];
require(proposal.end >= block.timestamp, "ERR_ENDED");
_;
}
/**
* @notice allows execution only when the proposal with given id has ended
*
* @param _id proposal id
*/
modifier proposalEnded(uint256 _id) {
Proposal memory proposal = proposals[_id];
require(proposal.end <= block.timestamp, "ERR_NOT_ENDED");
_;
}
/**
* @notice verifies that a value is greater than zero
*
* @param _value value to check for zero
*/
modifier greaterThanZero(uint256 _value) {
require(_value > 0, "ERR_ZERO_VALUE");
_;
}
/**
* @notice Updates the vote lock on the sender
*
* @param _proposalEnd proposal end time
*/
function updateVoteLock(uint256 _proposalEnd) private onlyStaker {
voteLocks[msg.sender] = Math.max(
voteLocks[msg.sender],
Math.max(_proposalEnd, voteLockDuration.add(block.timestamp))
);
}
/**
* @notice does the common vote finalization
*
* @param _id the id of the proposal to vote
* @param _for is this vote for or against the proposal
*/
function vote(uint256 _id, bool _for)
private
onlyStaker
proposalExists(_id)
proposalOpen(_id)
proposalNotEnded(_id)
{
Proposal storage proposal = proposals[_id];
if (_for) {
uint256 votesAgainst = proposal.votesAgainst[msg.sender];
// do we have against votes for this sender?
if (votesAgainst > 0) {
// yes, remove the against votes first
proposal.totalVotesAgainst = proposal.totalVotesAgainst.sub(votesAgainst);
proposal.votesAgainst[msg.sender] = 0;
}
} else {
// get against votes for this sender
uint256 votesFor = proposal.votesFor[msg.sender];
// do we have for votes for this sender?
if (votesFor > 0) {
proposal.totalVotesFor = proposal.totalVotesFor.sub(votesFor);
proposal.votesFor[msg.sender] = 0;
}
}
// calculate voting power in case voting against twice
uint256 voteAmount = votesOf(msg.sender).sub(
_for ? proposal.votesFor[msg.sender] : proposal.votesAgainst[msg.sender]
);
if (_for) {
// increase total for votes of the proposal
proposal.totalVotesFor = proposal.totalVotesFor.add(voteAmount);
// set for votes to the votes of the sender
proposal.votesFor[msg.sender] = votesOf(msg.sender);
} else {
// increase total against votes of the proposal
proposal.totalVotesAgainst = proposal.totalVotesAgainst.add(voteAmount);
// set against votes to the votes of the sender
proposal.votesAgainst[msg.sender] = votesOf(msg.sender);
}
// update total votes available on the proposal
proposal.totalAvailableVotes = totalVotes;
// recalculate quorum based on overall votes
proposal.quorum = calculateQuorumRatio(proposal);
// update vote lock
updateVoteLock(proposal.end);
// emit vote event
emit Vote(proposal.id, msg.sender, _for, voteAmount);
}
/**
* @notice returns the quorum ratio of a proposal
*
* @param _proposal proposal
* @return quorum ratio
*/
function calculateQuorumRatio(Proposal memory _proposal) internal view returns (uint256) {
// calculate overall votes
uint256 totalProposalVotes = _proposal.totalVotesFor.add(_proposal.totalVotesAgainst);
return totalProposalVotes.mul(PPM_RESOLUTION).div(totalVotes);
}
/**
* @notice removes the caller's entire stake
*/
function exit() external {
unstake(votesOf(msg.sender));
}
/**
* @notice returns the voting stats of a proposal
*
* @param _id proposal id
* @return votes for ratio
* @return votes against ratio
* @return quorum ratio
*/
function proposalStats(uint256 _id)
public
view
returns (
uint256,
uint256,
uint256
)
{
Proposal memory proposal = proposals[_id];
uint256 forRatio = proposal.totalVotesFor;
uint256 againstRatio = proposal.totalVotesAgainst;
// calculate overall total votes
uint256 totalProposalVotes = forRatio.add(againstRatio);
// calculate for votes ratio
forRatio = forRatio.mul(PPM_RESOLUTION).div(totalProposalVotes);
// calculate against votes ratio
againstRatio = againstRatio.mul(PPM_RESOLUTION).div(totalProposalVotes);
// calculate quorum ratio
uint256 quorumRatio = totalProposalVotes.mul(PPM_RESOLUTION).div(
proposal.totalAvailableVotes
);
return (forRatio, againstRatio, quorumRatio);
}
/**
* @notice returns the voting power of a given address
*
* @param _voter voter address
* @return votes of given address
*/
function votesOf(address _voter) public view returns (uint256) {
return votes[_voter];
}
/**
* @notice returns the voting power of a given address against a given proposal
*
* @param _voter voter address
* @param _id proposal id
* @return votes of given address against given proposal
*/
function votesAgainstOf(address _voter, uint256 _id) public view returns (uint256) {
return proposals[_id].votesAgainst[_voter];
}
/**
* @notice returns the voting power of a given address for a given proposal
*
* @param _voter voter address
* @param _id proposal id
* @return votes of given address for given proposal
*/
function votesForOf(address _voter, uint256 _id) public view returns (uint256) {
return proposals[_id].votesFor[_voter];
}
/**
* @notice updates the quorum needed for proposals to pass
*
* @param _quorum required quorum
*/
function setQuorum(uint256 _quorum) public ownerOnly greaterThanZero(_quorum) {
// check quorum for not being above 100
require(_quorum <= PPM_RESOLUTION, "ERR_QUORUM_TOO_HIGH");
quorum = _quorum;
emit QuorumUpdated(_quorum);
}
/**
* @notice updates the minimum stake required to create a new proposal
*
* @param _minimum minimum stake
*/
function setNewProposalMinimum(uint256 _minimum) public ownerOnly greaterThanZero(_minimum) {
require(_minimum <= govToken.totalSupply(), "ERR_EXCEEDS_TOTAL_SUPPLY");
newProposalMinimum = _minimum;
emit NewProposalMinimumUpdated(_minimum);
}
/**
* @notice updates the proposals voting duration
*
* @param _voteDuration vote duration
*/
function setVoteDuration(uint256 _voteDuration)
public
ownerOnly
greaterThanZero(_voteDuration)
{
voteDuration = _voteDuration;
emit VoteDurationUpdated(_voteDuration);
}
/**
* @notice updates the post vote lock duration
*
* @param _duration new vote lock duration
*/
function setVoteLockDuration(uint256 _duration) public ownerOnly greaterThanZero(_duration) {
voteLockDuration = _duration;
emit VoteLockDurationUpdated(_duration);
}
/**
* @notice creates a new proposal
*
* @param _executor the address of the contract that will execute the proposal after it passes
* @param _hash ipfs hash of the proposal description
*/
function propose(address _executor, string memory _hash) public {
require(votesOf(msg.sender) >= newProposalMinimum, "ERR_INSUFFICIENT_STAKE");
uint256 id = proposalCount;
// increment proposal count so next proposal gets the next higher id
proposalCount = proposalCount.add(1);
// create new proposal
Proposal memory proposal = Proposal({
id: id,
proposer: msg.sender,
totalVotesFor: 0,
totalVotesAgainst: 0,
start: block.timestamp,
end: voteDuration.add(block.timestamp),
executor: _executor,
hash: _hash,
totalAvailableVotes: totalVotes,
quorum: 0,
quorumRequired: quorum,
open: true,
executed: false
});
proposals[id] = proposal;
// lock proposer
updateVoteLock(proposal.end);
// emit proposal event
emit NewProposal(id, proposal.start, voteDuration, proposal.proposer, proposal.executor);
}
/**
* @notice executes a proposal
*
* @param _id id of the proposal to execute
*/
function execute(uint256 _id) public proposalExists(_id) proposalEnded(_id) {
// check for executed status
require(!proposals[_id].executed, "ERR_ALREADY_EXECUTED");
// get voting info of proposal
(uint256 forRatio, uint256 againstRatio, uint256 quorumRatio) = proposalStats(_id);
// check proposal state
require(quorumRatio >= proposals[_id].quorumRequired, "ERR_NO_QUORUM");
// if the proposal is still open
if (proposals[_id].open) {
// tally votes
tallyVotes(_id);
}
// set executed
proposals[_id].executed = true;
// do execution on the contract to be executed
// note that this is a safe call as it was part of the proposal that was voted on
IExecutor(proposals[_id].executor).execute(_id, forRatio, againstRatio, quorumRatio);
// emit proposal executed event
emit ProposalExecuted(_id, proposals[_id].executor);
}
/**
* @notice tallies votes of proposal with given id
*
* @param _id id of the proposal to tally votes for
*/
function tallyVotes(uint256 _id)
public
proposalExists(_id)
proposalOpen(_id)
proposalEnded(_id)
{
// get voting info of proposal
(uint256 forRatio, uint256 againstRatio, ) = proposalStats(_id);
// do we have a quorum?
bool quorumReached = proposals[_id].quorum >= proposals[_id].quorumRequired;
// close proposal
proposals[_id].open = false;
// emit proposal finished event
emit ProposalFinished(_id, forRatio, againstRatio, quorumReached);
}
/**
* @notice stakes vote tokens
*
* @param _amount amount of vote tokens to stake
*/
function stake(uint256 _amount) public greaterThanZero(_amount) {
// increase vote power
votes[msg.sender] = votesOf(msg.sender).add(_amount);
// increase total votes
totalVotes = totalVotes.add(_amount);
// transfer tokens to this contract
govToken.safeTransferFrom(msg.sender, address(this), _amount);
// lock staker to avoid flashloans messing around with total votes
voteLocks[msg.sender] = Math.max(
voteLocks[msg.sender],
Math.max(voteLockDuration.div(voteLockFraction), 10 minutes).add(block.timestamp)
);
// emit staked event
emit Staked(msg.sender, _amount);
}
/**
* @notice unstakes vote tokens
*
* @param _amount amount of vote tokens to unstake
*/
function unstake(uint256 _amount) public greaterThanZero(_amount) {
require(voteLocks[msg.sender] < block.timestamp, "ERR_LOCKED");
// reduce votes for user
votes[msg.sender] = votesOf(msg.sender).sub(_amount);
// reduce total votes
totalVotes = totalVotes.sub(_amount);
// transfer tokens back
govToken.safeTransfer(msg.sender, _amount);
// emit unstaked event
emit Unstaked(msg.sender, _amount);
}
/**
* @notice votes for a proposal
*
* @param _id id of the proposal to vote for
*/
function voteFor(uint256 _id) public {
vote(_id, true);
}
/**
* @notice votes against a proposal
*
* @param _id id of the proposal to vote against
*/
function voteAgainst(uint256 _id) public {
vote(_id, false);
}
}
| * @notice triggered when the vote lock duration is updated @param _duration new vote lock duration/ | event VoteLockDurationUpdated(uint256 _duration);
| 2,517,620 | [
1,
10668,
329,
1347,
326,
12501,
2176,
3734,
353,
3526,
225,
389,
8760,
394,
12501,
2176,
3734,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
27540,
2531,
5326,
7381,
12,
11890,
5034,
389,
8760,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x20Ee1c052e2726Da0DD8774b1CCBc38803A90e9a/sources/YYY.sol | * @dev ERC721 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 ERC721Pausable is ERC721, Ownable, Pausable {
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (_msgSender() != owner()) {
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (_msgSender() != owner()) {
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
}
| 3,170,816 | [
1,
654,
39,
27,
5340,
1147,
598,
6790,
16665,
1147,
29375,
16,
312,
474,
310,
471,
18305,
310,
18,
19256,
364,
22456,
4123,
487,
5309,
310,
1284,
5489,
3180,
326,
679,
434,
392,
9873,
3879,
16,
578,
7999,
392,
801,
24530,
1620,
364,
4843,
94,
310,
777,
1147,
29375,
316,
326,
871,
434,
279,
7876,
7934,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
8770,
6835,
4232,
39,
27,
5340,
16507,
16665,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
16,
21800,
16665,
288,
203,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
2713,
5024,
3849,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
3639,
309,
261,
67,
3576,
12021,
1435,
480,
3410,
10756,
288,
203,
5411,
2583,
12,
5,
8774,
3668,
9334,
315,
654,
39,
27,
5340,
16507,
16665,
30,
1147,
7412,
1323,
17781,
8863,
203,
3639,
289,
203,
565,
289,
203,
565,
262,
2713,
5024,
3849,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
3639,
309,
261,
67,
3576,
12021,
1435,
480,
3410,
10756,
288,
203,
5411,
2583,
12,
5,
8774,
3668,
9334,
315,
654,
39,
27,
5340,
16507,
16665,
30,
1147,
7412,
1323,
17781,
8863,
203,
3639,
289,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./MultiRewardsLiquidityMiningManager.sol";
import "./TimeLockPool.sol";
import "./MultiRewardsTimeLockPool.sol";
/// @dev reader contract to easily fetch all relevant info for an account
contract MultiRewardsView {
struct Data {
uint256 pendingRewards;
Pool[] pools;
Pool escrowPool;
uint256 totalWeight;
}
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
uint256 multiplier;
}
struct Pool {
address poolAddress;
uint256 totalPoolShares;
address depositToken;
uint256 accountPendingRewards;
uint256 accountClaimedRewards;
uint256 accountTotalDeposit;
uint256 accountPoolShares;
uint256 weight;
Deposit[] deposits;
}
MultiRewardsLiquidityMiningManager public immutable liquidityMiningManager;
TimeLockPool public immutable escrowPool;
constructor(address _liquidityMiningManager, address _escrowPool) {
liquidityMiningManager = MultiRewardsLiquidityMiningManager(_liquidityMiningManager);
escrowPool = TimeLockPool(_escrowPool);
}
function fetchData(address _account) external view returns (Data memory result) {
uint256 rewardPerSecond = liquidityMiningManager.rewardPerSecond();
uint256 lastDistribution = liquidityMiningManager.lastDistribution();
uint256 pendingRewards = rewardPerSecond * (block.timestamp - lastDistribution);
result.pendingRewards = pendingRewards;
result.totalWeight = liquidityMiningManager.totalWeight();
MultiRewardsLiquidityMiningManager.Pool[] memory pools = liquidityMiningManager.getPools();
result.pools = new Pool[](pools.length);
for(uint256 i = 0; i < pools.length; i ++) {
MultiRewardsTimeLockPool poolContract = MultiRewardsTimeLockPool(address(pools[i].poolContract));
address reward = address(liquidityMiningManager.reward());
result.pools[i] = Pool({
poolAddress: address(pools[i].poolContract),
totalPoolShares: poolContract.totalSupply(),
depositToken: address(poolContract.depositToken()),
accountPendingRewards: poolContract.withdrawableRewardsOf(reward, _account),
accountClaimedRewards: poolContract.withdrawnRewardsOf(reward, _account),
accountTotalDeposit: poolContract.getTotalDeposit(_account),
accountPoolShares: poolContract.balanceOf(_account),
weight: pools[i].weight,
deposits: new Deposit[](poolContract.getDepositsOfLength(_account))
});
MultiRewardsTimeLockPool.Deposit[] memory deposits = poolContract.getDepositsOf(_account);
for(uint256 j = 0; j < result.pools[i].deposits.length; j ++) {
MultiRewardsTimeLockPool.Deposit memory deposit = deposits[j];
result.pools[i].deposits[j] = Deposit({
amount: deposit.amount,
start: deposit.start,
end: deposit.end,
multiplier: poolContract.getMultiplier(deposit.end - deposit.start)
});
}
}
result.escrowPool = Pool({
poolAddress: address(escrowPool),
totalPoolShares: escrowPool.totalSupply(),
depositToken: address(escrowPool.depositToken()),
accountPendingRewards: escrowPool.withdrawableRewardsOf(_account),
accountClaimedRewards: escrowPool.withdrawnRewardsOf(_account),
accountTotalDeposit: escrowPool.getTotalDeposit(_account),
accountPoolShares: escrowPool.balanceOf(_account),
weight: 0,
deposits: new Deposit[](escrowPool.getDepositsOfLength(_account))
});
TimeLockPool.Deposit[] memory deposits = escrowPool.getDepositsOf(_account);
for(uint256 j = 0; j < result.escrowPool.deposits.length; j ++) {
TimeLockPool.Deposit memory deposit = deposits[j];
result.escrowPool.deposits[j] = Deposit({
amount: deposit.amount,
start: deposit.start,
end: deposit.end,
multiplier: escrowPool.getMultiplier(deposit.end - deposit.start)
});
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IMultiRewardsBasePool.sol";
import "./base/TokenSaver.sol";
contract MultiRewardsLiquidityMiningManager is TokenSaver {
using SafeERC20 for IERC20;
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256("REWARD_DISTRIBUTOR_ROLE");
uint256 public MAX_POOL_COUNT = 10;
IERC20 immutable public reward;
address immutable public rewardSource;
uint256 public rewardPerSecond; //total reward amount per second
uint256 public lastDistribution; //when rewards were last pushed
uint256 public totalWeight;
mapping(address => bool) public poolAdded;
Pool[] public pools;
struct Pool {
IMultiRewardsBasePool poolContract;
uint256 weight;
}
modifier onlyGov {
require(hasRole(GOV_ROLE, _msgSender()), "LiquidityMiningManager.onlyGov: permission denied");
_;
}
modifier onlyRewardDistributor {
require(hasRole(REWARD_DISTRIBUTOR_ROLE, _msgSender()), "LiquidityMiningManager.onlyRewardDistributor: permission denied");
_;
}
event PoolAdded(address indexed pool, uint256 weight);
event PoolRemoved(uint256 indexed poolId, address indexed pool);
event WeightAdjusted(uint256 indexed poolId, address indexed pool, uint256 newWeight);
event RewardsPerSecondSet(uint256 rewardsPerSecond);
event RewardsDistributed(address _from, uint256 indexed _amount);
constructor(address _reward, address _rewardSource) {
require(_reward != address(0), "LiquidityMiningManager.constructor: reward token must be set");
require(_rewardSource != address(0), "LiquidityMiningManager.constructor: rewardSource token must be set");
reward = IERC20(_reward);
rewardSource = _rewardSource;
}
function addPool(address _poolContract, uint256 _weight) external onlyGov {
distributeRewards();
require(_poolContract != address(0), "LiquidityMiningManager.addPool: pool contract must be set");
require(!poolAdded[_poolContract], "LiquidityMiningManager.addPool: Pool already added");
require(pools.length < MAX_POOL_COUNT, "LiquidityMiningManager.addPool: Max amount of pools reached");
// add pool
pools.push(Pool({
poolContract: IMultiRewardsBasePool(_poolContract),
weight: _weight
}));
poolAdded[_poolContract] = true;
// increase totalWeight
totalWeight += _weight;
// Approve max token amount
reward.safeApprove(_poolContract, type(uint256).max);
emit PoolAdded(_poolContract, _weight);
}
function removePool(uint256 _poolId) external onlyGov {
require(_poolId < pools.length, "LiquidityMiningManager.removePool: Pool does not exist");
distributeRewards();
address poolAddress = address(pools[_poolId].poolContract);
// decrease totalWeight
totalWeight -= pools[_poolId].weight;
// remove pool
pools[_poolId] = pools[pools.length - 1];
pools.pop();
poolAdded[poolAddress] = false;
// Approve 0 token amount
reward.safeApprove(poolAddress, 0);
emit PoolRemoved(_poolId, poolAddress);
}
function adjustWeight(uint256 _poolId, uint256 _newWeight) external onlyGov {
require(_poolId < pools.length, "LiquidityMiningManager.adjustWeight: Pool does not exist");
distributeRewards();
Pool storage pool = pools[_poolId];
totalWeight -= pool.weight;
totalWeight += _newWeight;
pool.weight = _newWeight;
emit WeightAdjusted(_poolId, address(pool.poolContract), _newWeight);
}
function setRewardPerSecond(uint256 _rewardPerSecond) external onlyGov {
distributeRewards();
rewardPerSecond = _rewardPerSecond;
emit RewardsPerSecondSet(_rewardPerSecond);
}
function distributeRewards() public onlyRewardDistributor {
uint256 timePassed = block.timestamp - lastDistribution;
uint256 totalRewardAmount = rewardPerSecond * timePassed;
lastDistribution = block.timestamp;
// return if pool length == 0
if(pools.length == 0) {
return;
}
// return if accrued rewards == 0
if(totalRewardAmount == 0) {
return;
}
reward.safeTransferFrom(rewardSource, address(this), totalRewardAmount);
for(uint256 i = 0; i < pools.length; i ++) {
Pool memory pool = pools[i];
uint256 poolRewardAmount = totalRewardAmount * pool.weight / totalWeight;
// Ignore tx failing to prevent a single pool from halting reward distribution
address(pool.poolContract).call(abi.encodeWithSelector(pool.poolContract.distributeRewards.selector, address(reward), poolRewardAmount));
}
uint256 leftOverReward = reward.balanceOf(address(this));
// send back excess but ignore dust
if(leftOverReward > 1) {
reward.safeTransfer(rewardSource, leftOverReward);
}
emit RewardsDistributed(_msgSender(), totalRewardAmount);
}
function getPools() external view returns(Pool[] memory result) {
return pools;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./base/BasePool.sol";
import "./interfaces/ITimeLockPool.sol";
contract TimeLockPool is BasePool, ITimeLockPool {
using Math for uint256;
using SafeERC20 for IERC20;
uint256 public immutable maxBonus;
uint256 public immutable maxLockDuration;
uint256 public constant MIN_LOCK_DURATION = 10 minutes;
uint256 public constant MAX_LOCK_DURATION = 36500 days;
mapping(address => Deposit[]) public depositsOf;
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
}
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address _rewardToken,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration,
uint256 _maxBonus,
uint256 _maxLockDuration
) BasePool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration) {
require(_maxLockDuration <= MAX_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be less than or equal to maximum lock duration");
require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration");
maxBonus = _maxBonus;
maxLockDuration = _maxLockDuration;
}
event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from);
event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount);
function deposit(uint256 _amount, uint256 _duration, address _receiver) external override nonReentrant {
require(_receiver != address(0), "TimeLockPool.deposit: receiver cannot be zero address");
require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0");
// Don't allow locking > maxLockDuration
uint256 duration = _duration.min(maxLockDuration);
// Enforce min lockup duration to prevent flash loan or MEV transaction ordering
duration = duration.max(MIN_LOCK_DURATION);
depositToken.safeTransferFrom(_msgSender(), address(this), _amount);
depositsOf[_receiver].push(Deposit({
amount: _amount,
start: uint64(block.timestamp),
end: uint64(block.timestamp) + uint64(duration)
}));
uint256 mintAmount = _amount * getMultiplier(duration) / 1e18;
_mint(_receiver, mintAmount);
emit Deposited(_amount, duration, _receiver, _msgSender());
}
function withdraw(uint256 _depositId, address _receiver) external nonReentrant {
require(_receiver != address(0), "TimeLockPool.withdraw: receiver cannot be zero address");
require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist");
Deposit memory userDeposit = depositsOf[_msgSender()][_depositId];
require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon");
// No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits
uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18;
// remove Deposit
depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1];
depositsOf[_msgSender()].pop();
// burn pool shares
_burn(_msgSender(), shareAmount);
// return tokens
depositToken.safeTransfer(_receiver, userDeposit.amount);
emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount);
}
function getMultiplier(uint256 _lockDuration) public view returns(uint256) {
return 1e18 + (maxBonus * _lockDuration / maxLockDuration);
}
function getTotalDeposit(address _account) public view returns(uint256) {
uint256 total;
for(uint256 i = 0; i < depositsOf[_account].length; i++) {
total += depositsOf[_account][i].amount;
}
return total;
}
function getDepositsOf(address _account) public view returns(Deposit[] memory) {
return depositsOf[_account];
}
function getDepositsOfLength(address _account) public view returns(uint256) {
return depositsOf[_account].length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./base/MultiRewardsBasePool.sol";
import "./interfaces/ITimeLockPool.sol";
contract MultiRewardsTimeLockPool is MultiRewardsBasePool, ITimeLockPool {
using Math for uint256;
using SafeERC20 for IERC20;
uint256 public immutable maxBonus;
uint256 public immutable maxLockDuration;
uint256 public constant MIN_LOCK_DURATION = 30 days;
mapping(address => Deposit[]) public depositsOf;
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
}
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address[] memory _rewardTokens,
address[] memory _escrowPools,
uint256[] memory _escrowPortions,
uint256[] memory _escrowDurations,
uint256 _maxBonus,
uint256 _maxLockDuration
) MultiRewardsBasePool(_name, _symbol, _depositToken, _rewardTokens, _escrowPools, _escrowPortions, _escrowDurations) {
require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration");
maxBonus = _maxBonus;
maxLockDuration = _maxLockDuration;
}
event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from);
event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount);
function deposit(uint256 _amount, uint256 _duration, address _receiver) external override nonReentrant {
require(_receiver != address(0), "TimeLockPool.deposit: receiver cannot be zero address");
require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0");
// Don't allow locking > maxLockDuration
uint256 duration = _duration.min(maxLockDuration);
// Enforce min lockup duration to prevent flash loan or MEV transaction ordering
duration = duration.max(MIN_LOCK_DURATION);
depositToken.safeTransferFrom(_msgSender(), address(this), _amount);
depositsOf[_receiver].push(Deposit({
amount: _amount,
start: uint64(block.timestamp),
end: uint64(block.timestamp) + uint64(duration)
}));
uint256 mintAmount = _amount * getMultiplier(duration) / 1e18;
_mint(_receiver, mintAmount);
emit Deposited(_amount, duration, _receiver, _msgSender());
}
function withdraw(uint256 _depositId, address _receiver) external nonReentrant {
require(_receiver != address(0), "TimeLockPool.withdraw: receiver cannot be zero address");
require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist");
Deposit memory userDeposit = depositsOf[_msgSender()][_depositId];
require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon");
// No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits
uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18;
// remove Deposit
depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1];
depositsOf[_msgSender()].pop();
// burn pool shares
_burn(_msgSender(), shareAmount);
// return tokens
depositToken.safeTransfer(_receiver, userDeposit.amount);
emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount);
}
function getMultiplier(uint256 _lockDuration) public view returns(uint256) {
return 1e18 + (maxBonus * _lockDuration / maxLockDuration);
}
function getTotalDeposit(address _account) public view returns(uint256) {
uint256 total;
for(uint256 i = 0; i < depositsOf[_account].length; i++) {
total += depositsOf[_account][i].amount;
}
return total;
}
function getDepositsOf(address _account) public view returns(Deposit[] memory) {
return depositsOf[_account];
}
function getDepositsOfLength(address _account) public view returns(uint256) {
return depositsOf[_account].length;
}
}
// 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'
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
pragma solidity 0.8.7;
interface IMultiRewardsBasePool {
function distributeRewards(address _reward, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
contract TokenSaver is AccessControlEnumerable {
using SafeERC20 for IERC20;
bytes32 public constant TOKEN_SAVER_ROLE = keccak256("TOKEN_SAVER_ROLE");
event TokenSaved(address indexed by, address indexed receiver, address indexed token, uint256 amount);
modifier onlyTokenSaver() {
require(hasRole(TOKEN_SAVER_ROLE, _msgSender()), "TokenSaver.onlyTokenSaver: permission denied");
_;
}
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function saveToken(address _token, address _receiver, uint256 _amount) external onlyTokenSaver {
IERC20(_token).safeTransfer(_receiver, _amount);
emit TokenSaved(_msgSender(), _receiver, _token, _amount);
}
}
// 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;
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
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// 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 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
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
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.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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IBasePool.sol";
import "../interfaces/ITimeLockPool.sol";
import "./AbstractRewards.sol";
import "./TokenSaver.sol";
abstract contract BasePool is ERC20Votes, AbstractRewards, IBasePool, TokenSaver, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeCast for uint256;
using SafeCast for int256;
IERC20 public immutable depositToken;
IERC20 public immutable rewardToken;
ITimeLockPool public immutable escrowPool;
uint256 public immutable escrowPortion; // how much is escrowed 1e18 == 100%
uint256 public immutable escrowDuration; // escrow duration in seconds
event RewardsClaimed(address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount);
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address _rewardToken,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration
) ERC20Permit(_name) ERC20(_name, _symbol) AbstractRewards(balanceOf, totalSupply) {
require(_escrowPortion <= 1e18, "BasePool.constructor: Cannot escrow more than 100%");
require(_depositToken != address(0), "BasePool.constructor: Deposit token must be set");
depositToken = IERC20(_depositToken);
rewardToken = IERC20(_rewardToken);
escrowPool = ITimeLockPool(_escrowPool);
escrowPortion = _escrowPortion;
escrowDuration = _escrowDuration;
if(_rewardToken != address(0) && _escrowPool != address(0)) {
IERC20(_rewardToken).safeApprove(_escrowPool, type(uint256).max);
}
}
function _mint(address _account, uint256 _amount) internal virtual override {
super._mint(_account, _amount);
_correctPoints(_account, -(_amount.toInt256()));
}
function _burn(address _account, uint256 _amount) internal virtual override {
super._burn(_account, _amount);
_correctPoints(_account, _amount.toInt256());
}
function _transfer(address _from, address _to, uint256 _value) internal virtual override {
super._transfer(_from, _to, _value);
_correctPointsForTransfer(_from, _to, _value);
}
function distributeRewards(uint256 _amount) external override nonReentrant {
rewardToken.safeTransferFrom(_msgSender(), address(this), _amount);
_distributeRewards(_amount);
}
function claimRewards(address _receiver) external {
uint256 rewardAmount = _prepareCollect(_msgSender());
uint256 escrowedRewardAmount = rewardAmount * escrowPortion / 1e18;
uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount;
if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) {
escrowPool.deposit(escrowedRewardAmount, escrowDuration, _receiver);
}
// ignore dust
if(nonEscrowedRewardAmount > 1) {
rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount);
}
emit RewardsClaimed(_msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface ITimeLockPool {
function deposit(uint256 _amount, uint256 _duration, address _receiver) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-ERC20Permit.sol";
import "../../../utils/math/Math.sol";
import "../../../utils/math/SafeCast.sol";
import "../../../utils/cryptography/ECDSA.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20Votes is ERC20Permit {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = Math.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
return _delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
return _delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IBasePool {
function distributeRewards(uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/IAbstractRewards.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/**
* @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol
* Renamed dividends to rewards.
* @dev (OLD) Many functions in this contract were taken from this repository:
* https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol
* which is an example implementation of ERC 2222, the draft for which can be found at
* https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md
*
* This contract has been substantially modified from the original and does not comply with ERC 2222.
* Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated
* into this abstract contract which can be inherited by anything tracking ownership of reward shares.
*/
abstract contract AbstractRewards is IAbstractRewards {
using SafeCast for uint128;
using SafeCast for uint256;
using SafeCast for int256;
/* ======== Constants ======== */
uint128 public constant POINTS_MULTIPLIER = type(uint128).max;
event PointsCorrectionUpdated(address indexed account, int256 points);
/* ======== Internal Function References ======== */
function(address) view returns (uint256) private immutable getSharesOf;
function() view returns (uint256) private immutable getTotalShares;
/* ======== Storage ======== */
uint256 public pointsPerShare;
mapping(address => int256) public pointsCorrection;
mapping(address => uint256) public withdrawnRewards;
constructor(
function(address) view returns (uint256) getSharesOf_,
function() view returns (uint256) getTotalShares_
) {
getSharesOf = getSharesOf_;
getTotalShares = getTotalShares_;
}
/* ======== Public View Functions ======== */
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param _account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address _account) public view override returns (uint256) {
return cumulativeRewardsOf(_account) - withdrawnRewards[_account];
}
/**
* @notice View the amount of rewards that an address has withdrawn.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has withdrawn.
*/
function withdrawnRewardsOf(address _account) public view override returns (uint256) {
return withdrawnRewards[_account];
}
/**
* @notice View the amount of rewards that an address has earned in total.
* @dev accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has earned in total.
*/
function cumulativeRewardsOf(address _account) public view override returns (uint256) {
return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER;
}
/* ======== Dividend Utility Functions ======== */
/**
* @notice Distributes rewards to token holders.
* @dev It reverts if the total shares is 0.
* It emits the `RewardsDistributed` event if the amount to distribute is greater than 0.
* About undistributed rewards:
* In each distribution, there is a small amount which does not get distributed,
* which is `(amount * POINTS_MULTIPLIER) % totalShares()`.
* With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting
* distributed in a distribution can be less than 1 (base unit).
*/
function _distributeRewards(uint256 _amount) internal {
uint256 shares = getTotalShares();
require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero");
if (_amount > 0) {
pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares);
emit RewardsDistributed(msg.sender, _amount);
}
}
/**
* @notice Prepares collection of owed rewards
* @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is
* greater than 0.
*/
function _prepareCollect(address _account) internal returns (uint256) {
require(_account != address(0), "AbstractRewards._prepareCollect: account cannot be zero address");
uint256 _withdrawableDividend = withdrawableRewardsOf(_account);
if (_withdrawableDividend > 0) {
withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend;
emit RewardsWithdrawn(_account, _withdrawableDividend);
}
return _withdrawableDividend;
}
function _correctPointsForTransfer(address _from, address _to, uint256 _shares) internal {
require(_from != address(0), "AbstractRewards._correctPointsForTransfer: address cannot be zero address");
require(_to != address(0), "AbstractRewards._correctPointsForTransfer: address cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPointsForTransfer: shares cannot be zero");
int256 _magCorrection = (pointsPerShare * _shares).toInt256();
pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection;
pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection;
emit PointsCorrectionUpdated(_from, pointsCorrection[_from]);
emit PointsCorrectionUpdated(_to, pointsCorrection[_to]);
}
/**
* @dev Increases or decreases the points correction for `account` by
* `shares*pointsPerShare`.
*/
function _correctPoints(address _account, int256 _shares) internal {
require(_account != address(0), "AbstractRewards._correctPoints: account cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPoints: shares cannot be zero");
pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (pointsPerShare.toInt256()));
emit PointsCorrectionUpdated(_account, pointsCorrection[_account]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
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 Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IAbstractRewards {
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has withdrawn.
* @param account The address of a token holder.
* @return The amount of funds that `account` has withdrawn.
*/
function withdrawnRewardsOf(address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has earned in total.
* accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER
* @param account The address of a token holder.
* @return The amount of funds that `account` has earned in total.
*/
function cumulativeRewardsOf(address account) external view returns (uint256);
/**
* @dev This event emits when new funds are distributed
* @param by the address of the sender who distributed funds
* @param rewardsDistributed the amount of funds received for distribution
*/
event RewardsDistributed(address indexed by, uint256 rewardsDistributed);
/**
* @dev This event emits when distributed funds are withdrawn by a token holder.
* @param by the address of the receiver of funds
* @param fundsWithdrawn the amount of funds that were withdrawn
*/
event RewardsWithdrawn(address indexed by, uint256 fundsWithdrawn);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IMultiRewardsBasePool.sol";
import "../interfaces/ITimeLockPool.sol";
import "./AbstractMultiRewards.sol";
import "./TokenSaver.sol";
abstract contract MultiRewardsBasePool is ERC20Votes, AbstractMultiRewards, IMultiRewardsBasePool, TokenSaver, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeCast for uint256;
using SafeCast for int256;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
IERC20 public immutable depositToken;
address[] public rewardTokens;
mapping(address => bool) public rewardTokensList;
mapping(address => address) public escrowPools;
mapping(address => uint256) public escrowPortions; // how much is escrowed 1e18 == 100%
mapping(address => uint256) public escrowDurations; // escrow duration in seconds
event RewardsClaimed(address indexed _reward, address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount);
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address[] memory _rewardTokens,
address[] memory _escrowPools,
uint256[] memory _escrowPortions,
uint256[] memory _escrowDurations
) ERC20Permit(_name) ERC20(_name, _symbol) AbstractMultiRewards(balanceOf, totalSupply) {
require(_depositToken != address(0), "MultiRewardsBasePool.constructor: Deposit token must be set");
require(_rewardTokens.length == _escrowPools.length, "MultiRewardsBasePool.constructor: reward tokens and escrow pools length mismatch");
require(_rewardTokens.length == _escrowPortions.length, "MultiRewardsBasePool.constructor: reward tokens and escrow portions length mismatch");
require(_rewardTokens.length == _escrowDurations.length, "MultiRewardsBasePool.constructor: reward tokens and escrow durations length mismatch");
depositToken = IERC20(_depositToken);
for (uint i=0; i<_rewardTokens.length; i++) {
address rewardToken = _rewardTokens[i];
require(rewardToken != address(0), "MultiRewardsBasePool.constructor: reward token cannot be zero address");
address escrowPool = _escrowPools[i];
uint256 escrowPortion = _escrowPortions[i];
require(escrowPortion <= 1e18, "MultiRewardsBasePool.constructor: Cannot escrow more than 100%");
uint256 escrowDuration = _escrowDurations[i];
if (!rewardTokensList[rewardToken]) {
rewardTokensList[rewardToken] = true;
rewardTokens.push(rewardToken);
escrowPools[rewardToken] = escrowPool;
escrowPortions[rewardToken] = escrowPortion;
escrowDurations[rewardToken] = escrowDuration;
if(rewardToken != address(0) && escrowPool != address(0)) {
IERC20(rewardToken).safeApprove(escrowPool, type(uint256).max);
}
}
}
_setupRole(ADMIN_ROLE, msg.sender);
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
}
/// @dev A modifier which checks that the caller has the admin role.
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, msg.sender), "MultiRewardsBasePool: only admin");
_;
}
function _mint(address _account, uint256 _amount) internal virtual override {
super._mint(_account, _amount);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPoints(reward, _account, -(_amount.toInt256()));
}
}
function _burn(address _account, uint256 _amount) internal virtual override {
super._burn(_account, _amount);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPoints(reward, _account, _amount.toInt256());
}
}
function _transfer(address _from, address _to, uint256 _value) internal virtual override {
super._transfer(_from, _to, _value);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPointsForTransfer(reward, _from, _to, _value);
}
}
function rewardTokensLength() external view returns (uint256) {
return rewardTokens.length;
}
function addRewardToken(
address _reward,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration)
external onlyAdmin
{
require(_reward != address(0), "MultiRewardsBasePool.addRewardToken: reward token cannot be zero address");
require(_escrowPortion <= 1e18, "MultiRewardsBasePool.addRewardToken: Cannot escrow more than 100%");
if (!rewardTokensList[_reward]) {
rewardTokensList[_reward] = true;
rewardTokens.push(_reward);
escrowPools[_reward] = _escrowPool;
escrowPortions[_reward] = _escrowPortion;
escrowDurations[_reward] = _escrowDuration;
if(_reward != address(0) && _escrowPool != address(0)) {
IERC20(_reward).safeApprove(_escrowPool, type(uint256).max);
}
}
}
function updateRewardToken(address _reward, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration) external onlyAdmin {
require(rewardTokensList[_reward], "MultiRewardsBasePool.updateRewardToken: reward token not in the list");
require(_reward != address(0), "MultiRewardsBasePool.updateRewardToken: reward token cannot be zero address");
require(_escrowPortion <= 1e18, "MultiRewardsBasePool.updateRewardToken: Cannot escrow more than 100%");
if (escrowPools[_reward] != _escrowPool && _escrowPool != address(0)) {
IERC20(_reward).safeApprove(_escrowPool, type(uint256).max);
}
escrowPools[_reward] = _escrowPool;
escrowPortions[_reward] = _escrowPortion;
escrowDurations[_reward] = _escrowDuration;
}
function distributeRewards(address _reward, uint256 _amount) external override nonReentrant {
IERC20(_reward).safeTransferFrom(_msgSender(), address(this), _amount);
_distributeRewards(_reward, _amount);
}
function claimRewards(address _reward, address _receiver) public {
uint256 rewardAmount = _prepareCollect(_reward, _msgSender());
uint256 escrowedRewardAmount = rewardAmount * escrowPortions[_reward] / 1e18;
uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount;
ITimeLockPool escrowPool = ITimeLockPool(escrowPools[_reward]);
if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) {
escrowPool.deposit(escrowedRewardAmount, escrowDurations[_reward], _receiver);
}
// ignore dust
if(nonEscrowedRewardAmount > 1) {
IERC20(_reward).safeTransfer(_receiver, nonEscrowedRewardAmount);
}
emit RewardsClaimed(_reward, _msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount);
}
function claimAll(address _receiver) external {
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
claimRewards(reward, _receiver);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/IAbstractMultiRewards.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/**
* @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol
* Renamed dividends to rewards.
* @dev (OLD) Many functions in this contract were taken from this repository:
* https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol
* which is an example implementation of ERC 2222, the draft for which can be found at
* https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md
*
* This contract has been substantially modified from the original and does not comply with ERC 2222.
* Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated
* into this abstract contract which can be inherited by anything tracking ownership of reward shares.
*/
abstract contract AbstractMultiRewards is IAbstractMultiRewards {
using SafeCast for uint128;
using SafeCast for uint256;
using SafeCast for int256;
/* ======== Constants ======== */
uint128 public constant POINTS_MULTIPLIER = type(uint128).max;
event PointsCorrectionUpdated(address indexed reward, address indexed account, int256 points);
/* ======== Internal Function References ======== */
function(address) view returns (uint256) private immutable getSharesOf;
function() view returns (uint256) private immutable getTotalShares;
/* ======== Storage ======== */
mapping(address => uint256) public pointsPerShare; //reward token address => points per share
mapping(address => mapping(address => int256)) public pointsCorrection; //reward token address => mapping(user address => pointsCorrection)
mapping(address => mapping(address => uint256)) public withdrawnRewards; //reward token address => mapping(user address => withdrawnRewards)
constructor(
function(address) view returns (uint256) getSharesOf_,
function() view returns (uint256) getTotalShares_
) {
getSharesOf = getSharesOf_;
getTotalShares = getTotalShares_;
}
/* ======== Public View Functions ======== */
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param _reward Address of the reward token
* @param _account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address _reward, address _account) public view override returns (uint256) {
return cumulativeRewardsOf(_reward, _account) - withdrawnRewards[_reward][_account];
}
/**
* @notice View the amount of rewards that an address has withdrawn.
* @param _reward The address of the reward token.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has withdrawn.
*/
function withdrawnRewardsOf(address _reward, address _account) public view override returns (uint256) {
return withdrawnRewards[_reward][_account];
}
/**
* @notice View the amount of rewards that an address has earned in total.
* @dev accumulativeFundsOf(reward, account) = withdrawableRewardsOf(reward, account) + withdrawnRewardsOf(reward, account)
* = (pointsPerShare[reward] * balanceOf(account) + pointsCorrection[reward][account]) / POINTS_MULTIPLIER
* @param _reward The address of the reward token.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has earned in total.
*/
function cumulativeRewardsOf(address _reward, address _account) public view override returns (uint256) {
return ((pointsPerShare[_reward] * getSharesOf(_account)).toInt256() + pointsCorrection[_reward][_account]).toUint256() / POINTS_MULTIPLIER;
}
/* ======== Dividend Utility Functions ======== */
/**
* @notice Distributes rewards to token holders.
* @dev It reverts if the total shares is 0.
* It emits the `RewardsDistributed` event if the amount to distribute is greater than 0.
* About undistributed rewards:
* In each distribution, there is a small amount which does not get distributed,
* which is `(amount * POINTS_MULTIPLIER) % totalShares()`.
* With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting
* distributed in a distribution can be less than 1 (base unit).
*/
function _distributeRewards(address _reward, uint256 _amount) internal {
require(_reward != address(0), "AbstractRewards._distributeRewards: reward cannot be zero address");
uint256 shares = getTotalShares();
require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero");
if (_amount > 0) {
pointsPerShare[_reward] = pointsPerShare[_reward] + (_amount * POINTS_MULTIPLIER / shares);
emit RewardsDistributed(msg.sender, _reward, _amount);
}
}
/**
* @notice Prepares collection of owed rewards
* @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is
* greater than 0.
*/
function _prepareCollect(address _reward, address _account) internal returns (uint256) {
require(_reward != address(0), "AbstractRewards._prepareCollect: reward cannot be zero address");
require(_account != address(0), "AbstractRewards._prepareCollect: account cannot be zero address");
uint256 _withdrawableDividend = withdrawableRewardsOf(_reward, _account);
if (_withdrawableDividend > 0) {
withdrawnRewards[_reward][_account] = withdrawnRewards[_reward][_account] + _withdrawableDividend;
emit RewardsWithdrawn(_reward, _account, _withdrawableDividend);
}
return _withdrawableDividend;
}
function _correctPointsForTransfer(address _reward, address _from, address _to, uint256 _shares) internal {
require(_reward != address(0), "AbstractRewards._correctPointsForTransfer: reward address cannot be zero address");
require(_from != address(0), "AbstractRewards._correctPointsForTransfer: from address cannot be zero address");
require(_to != address(0), "AbstractRewards._correctPointsForTransfer: to address cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPointsForTransfer: shares cannot be zero");
int256 _magCorrection = (pointsPerShare[_reward] * _shares).toInt256();
pointsCorrection[_reward][_from] = pointsCorrection[_reward][_from] + _magCorrection;
pointsCorrection[_reward][_to] = pointsCorrection[_reward][_to] - _magCorrection;
emit PointsCorrectionUpdated(_reward, _from, pointsCorrection[_reward][_from]);
emit PointsCorrectionUpdated(_reward, _to, pointsCorrection[_reward][_to]);
}
/**
* @dev Increases or decreases the points correction for `account` by
* `shares*pointsPerShare[reward]`.
*/
function _correctPoints(address _reward, address _account, int256 _shares) internal {
require(_reward != address(0), "AbstractRewards._correctPoints: reward cannot be zero address");
require(_account != address(0), "AbstractRewards._correctPoints: account cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPoints: shares cannot be zero");
pointsCorrection[_reward][_account] = pointsCorrection[_reward][_account] + (_shares * (pointsPerShare[_reward].toInt256()));
emit PointsCorrectionUpdated(_reward, _account, pointsCorrection[_reward][_account]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IAbstractMultiRewards {
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param reward Address of the reward token
* @param account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has withdrawn.
* @param reward The address of the reward token.
* @param account The address of a token holder.
* @return The amount of funds that `account` has withdrawn.
*/
function withdrawnRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has earned in total.
* accumulativeFundsOf(reward, account) = withdrawableRewardsOf(reward, account) + withdrawnRewardsOf(reward, account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[reward][account]) / POINTS_MULTIPLIER
* @param reward The address of the reward token.
* @param account The address of a token holder.
* @return The amount of funds that `account` has earned in total.
*/
function cumulativeRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev This event emits when new funds are distributed
* @param by the address of the sender who distributed funds
* @param reward the address of the reward token
* @param rewardsDistributed the amount of funds received for distribution
*/
event RewardsDistributed(address indexed by, address indexed reward, uint256 rewardsDistributed);
/**
* @dev This event emits when distributed funds are withdrawn by a token holder.
* @param reward the address of the reward token
* @param by the address of the receiver of funds
* @param fundsWithdrawn the amount of funds that were withdrawn
*/
event RewardsWithdrawn(address indexed reward, address indexed by, uint256 fundsWithdrawn);
} | * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. Requirements: - `blockNumber` must have been already mined/ | function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
| 7,355 | [
1,
5767,
326,
1300,
434,
19588,
364,
1375,
4631,
68,
622,
326,
679,
434,
1375,
2629,
1854,
8338,
29076,
30,
300,
1375,
2629,
1854,
68,
1297,
1240,
2118,
1818,
1131,
329,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1689,
689,
29637,
12,
2867,
2236,
16,
2254,
5034,
1203,
1854,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
2629,
1854,
411,
1203,
18,
2696,
16,
315,
654,
39,
3462,
29637,
30,
1203,
486,
4671,
1131,
329,
8863,
203,
3639,
327,
389,
1893,
4139,
6609,
24899,
1893,
4139,
63,
4631,
6487,
1203,
1854,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0x5a05f17Da7e3897DC2d03ED616333Fad85607CE6/sources/project_/contracts/HeartBall.sol | * @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 `requestedDecrease`. NOTE: Although this function is designed to avoid double spending with {approval}, it can still be frontrunned, preventing any attempt of allowance reduction./ | function decreaseAllowance(
address spender,
uint256 requestedDecrease
) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < requestedDecrease) {
revert ERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
unchecked {
_approve(owner, spender, currentAllowance - requestedDecrease);
}
return true;
}
| 3,270,144 | [
1,
3641,
6478,
23850,
3304,
326,
1699,
1359,
17578,
358,
1375,
87,
1302,
264,
68,
635,
326,
4894,
18,
1220,
353,
392,
10355,
358,
288,
12908,
537,
97,
716,
848,
506,
1399,
487,
279,
20310,
360,
367,
364,
9688,
11893,
316,
288,
45,
654,
39,
3462,
17,
12908,
537,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
29076,
30,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
87,
1302,
264,
68,
1297,
1240,
1699,
1359,
364,
326,
4894,
434,
622,
4520,
1375,
19065,
23326,
448,
8338,
5219,
30,
2262,
18897,
333,
445,
353,
26584,
358,
4543,
1645,
272,
9561,
598,
288,
12908,
1125,
5779,
518,
848,
4859,
506,
284,
1949,
313,
318,
11748,
16,
5309,
310,
1281,
4395,
434,
1699,
1359,
20176,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
20467,
7009,
1359,
12,
203,
202,
202,
2867,
17571,
264,
16,
203,
202,
202,
11890,
5034,
3764,
23326,
448,
203,
202,
13,
1071,
5024,
1135,
261,
6430,
13,
288,
203,
202,
202,
2867,
3410,
273,
389,
3576,
12021,
5621,
203,
202,
202,
11890,
5034,
783,
7009,
1359,
273,
1699,
1359,
12,
8443,
16,
17571,
264,
1769,
203,
202,
202,
430,
261,
2972,
7009,
1359,
411,
3764,
23326,
448,
13,
288,
203,
1082,
202,
266,
1097,
4232,
39,
3462,
2925,
23326,
448,
7009,
1359,
12,
87,
1302,
264,
16,
783,
7009,
1359,
16,
3764,
23326,
448,
1769,
203,
202,
202,
97,
203,
202,
202,
5847,
288,
203,
1082,
202,
67,
12908,
537,
12,
8443,
16,
17571,
264,
16,
783,
7009,
1359,
300,
3764,
23326,
448,
1769,
203,
202,
202,
97,
203,
203,
202,
202,
2463,
638,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// import "ethereum-datetime/contracts/DateTime.sol";
import "./DateTime.sol";
// our BookingToken
import "./Token.sol";
/// @title A traditional, fixed-price business (Bed and Breakfast) run on Ethereum. Includes a token + schedule system.
/// @author Ryan "Lamby" Lambert
/// @notice 1 token is always = 1 day accomodation. The USD price of the token can change. Appointments are scheduled in epoch time.
/// @dev Example project to be used on Rinkeby test network
contract Hotel {
// to prevent overflows, use SafeMath
using SafeMath for uint256;
using SafeMath for uint64;
// 1 token = 1 day accomodation
BookingToken public bookingToken;
// used for time conversions
DateTime private dateTime;
// used to return a static price
bool private useFixedPricing;
// the owner can access all functions
address payable public owner;
// price of a token in USD
uint64 public bookingTokenPrice;
// minimum year someone can schedule an appointment
uint256 CONTRACT_DEPLOY_TIME;
// used to determine amount of ETH to send in transaction
AggregatorV3Interface internal priceFeed;
// primary appointment storage
struct Appointment {
bool isAppointment;
string partyName;
address userAddress;
}
// user appointment info - saved in userBookings array
struct UserBooking {
uint256 timestamp;
uint8 numDays;
}
// this contract uses epoch/unix time to determine booking days; keys must be mod 86400
mapping(uint256 => Appointment) scheduleByTimestamp;
// list of all timestamps for a given user; key is user address
// set an array length if you are worried about variable gas consumption
mapping(address => UserBooking[]) public userBookings;
// emitted when user changes
event OwnerChanged(address indexed from, address to);
// emitted when price of the token changes
event TokenPriceChanged(uint64 oldPrice, uint64 newPrice);
// emitted when user buys a token
event TokenBought(address indexed from, uint256 sum, uint64 price);
// emitted when user schedules an appointment
event AppointmentScheduled(
address indexed from,
uint256 timestamp,
uint256 sum
);
// emitted when user refunds an appointment
event AppointmentRefunded(
address indexed from,
uint256 timestamp,
uint256 sum
);
// restricts access to owner role
modifier onlyOwner() {
require(msg.sender == owner, "owner restricted funtionality");
_;
}
// month is > 0 < 13, year is above contract deploy date
modifier validMonth(uint8 _m) {
require(_m > 0 && _m < 13, "Month must be 1 - 12 value");
_;
}
// day is a valid 1 - 31 number value
modifier validDay(uint8 _d) {
require(_d > 0 && _d < 32, "Invalid day");
_;
}
// numDays > 0
modifier validNumDays(uint8 _num) {
require(_num > 0, "Must be a value above 0");
_;
}
// timestamp cannot be before CONTRACT_DEPLOY_TIME && must be mod 0
// this is because we use unix days as our mapping keys
modifier validTimestamp(uint256 _t) {
validateTimestamp(_t);
_;
}
// valid read range - can't request more than 365 days at a time and timestamp must be mod 86400
modifier validRange(uint256 _t, uint8 _r) {
isMod86400(_t);
require(_r <= 365 && _r > 0, "Valid ranges are 1 - 365");
_;
}
// name can't be empty
modifier validName(string memory _s) {
require(bytes(_s).length != 0, "Party name cannot be blank");
_;
}
constructor(
uint64 _initialPrice,
address _priceContractAddr,
bool _useFixedPricing
) {
useFixedPricing = _useFixedPricing;
CONTRACT_DEPLOY_TIME = block.timestamp;
bookingToken = new BookingToken(address(this));
owner = payable(msg.sender);
// Rinkeby ETH/USD
priceFeed = AggregatorV3Interface(_priceContractAddr);
// DateTime Helper Contract
dateTime = new DateTime();
bookingTokenPrice = _initialPrice;
}
// timestamp cannot be before CONTRACT_DEPLOY_TIME && must be mod 0
// this is because we use unix days as our mapping keys
function validateTimestamp(uint256 _t) private view {
require(
_t > CONTRACT_DEPLOY_TIME,
"Cannot use any timestamp before the contract deploy timestamp"
);
isMod86400(_t);
}
function isMod86400(uint256 _t) private pure {
require(
_t.mod(86400) == 0,
"Timestamp must be mod 86400; try using getUnixTimestamp for a given month, day, year"
);
}
/// @notice Helper to get a unix timestamp given month, day, year.
/// @dev Can be calculated on the front-end but here's a shortcut :]
/// @return uint256
function getUnixTimestamp(
uint8 _month,
uint8 _day,
uint16 _year
) public view returns (uint256) {
return dateTime.toTimestamp(_year, _month, _day);
}
/// @notice Shortcut to return balanceOf a given address from our token contract
/// @dev you can just call the bookingToken function directly once you know the address; I set it to private and just included this function since its all thats relevant to our example
/// @return uint256
function getTokenBalance(address _address) public view returns (uint256) {
return bookingToken.balanceOf(_address);
}
/// @notice Helper to return all bookings for a given address
/// @dev userBookings is a dynamic array, so this function is meant to be read-only and should not be used in any state-altering functionality
/// @return Array[]
function getAppointmentsByUser(address _addr)
public
view
returns (UserBooking[] memory)
{
return userBookings[_addr];
}
/// @notice Returns an array of eventIDs for a given range
/// @return eventID[uint256]
function getRangeAvailability(uint256 _start, uint8 _numDays)
public
view
validRange(_start, _numDays)
returns (address[] memory)
{
uint8 i = 0;
// up to 31 days in a month
address[] memory monthlyAppointments = new address[](_numDays);
for (i; i < _numDays; i++) {
Appointment memory foundAppointment = scheduleByTimestamp[
_start + (i * 86400)
];
if (foundAppointment.isAppointment) {
monthlyAppointments[i] = foundAppointment.userAddress;
}
}
// returns an array with the correct number of days
return monthlyAppointments;
}
/// @notice Allows user to schedule an appointment at the hotel
/// @dev timestamp must be mod 86400 and _numDays must match total tickets
function bookAppointment(
string memory _name,
uint256 _timestamp,
uint8 _numDays
)
public
validName(_name)
validTimestamp(_timestamp)
validNumDays(_numDays)
{
bookingToken.burn(msg.sender, _numDays);
uint8 i = 0;
for (i; i < _numDays; i++) {
// Solidity reverts state changes when require is violated
// this allows us to loop through and create the necessary stateChanges in 1 for loop
require(
scheduleByTimestamp[_timestamp + (86400 * i)].isAppointment !=
true,
"Appointment already exists on one or more of the requested dates"
);
// save each booking day indexed by timestamp; this makes it easy to look up a range of days by unix uint256 mod 86400
scheduleByTimestamp[_timestamp + (86400 * i)] = Appointment(
true,
_name,
msg.sender
);
}
// save all user timestamps in array - we can use the timestamp + numDays as keys to our primary Appointment mapping
userBookings[msg.sender].push(UserBooking(_timestamp, _numDays));
emit AppointmentScheduled(msg.sender, _timestamp, _numDays);
}
function removeUserBooking(uint256 _indexToDelete) internal {
require(_indexToDelete < userBookings[msg.sender].length);
userBookings[msg.sender][_indexToDelete] = userBookings[msg.sender][
userBookings[msg.sender].length - 1
];
userBookings[msg.sender].pop();
}
/// @notice Allows user to refund any appointment
/// @dev for a production app you should cap maxRedemptions for users to avoid cancellation abuse
function refundAppointment(uint8 _index) public {
// first get the timestamp and numdays from timestamp from the index
uint256 timestamp = userBookings[msg.sender][_index].timestamp;
uint8 numDays = userBookings[msg.sender][_index].numDays;
require(timestamp > 0 && numDays > 0, "no booking found at that index");
validateTimestamp(timestamp);
// cannot cancel past events
require(
timestamp > block.timestamp,
"cannot cancel events in the past"
);
uint8 i = 0;
for (i; i < numDays; i++) {
uint256 currDay = timestamp + (86400 * i);
// Solidity reverts state changes when require is violated
// this allows us to loop through and create the necessary stateChanges in 1 for loop
require(
scheduleByTimestamp[currDay].isAppointment == true,
"Appointment does not exist"
);
require(
scheduleByTimestamp[currDay].userAddress == msg.sender,
"Cannot refund an appointment msg.sender did not create"
);
// this effectively deletes the event
scheduleByTimestamp[currDay].isAppointment = false;
}
// this removes the booking from the user array
removeUserBooking(_index);
// refund the user by minting more tokens
bookingToken.mint(msg.sender, numDays);
// emit an event so UI can update
emit AppointmentRefunded(msg.sender, timestamp, numDays);
}
/// @notice Allows the current owner role to be passed to a new owner
/// @dev owner controls pretty much everything so pass with care
function passOwnerRole(address _owner) public onlyOwner {
owner = payable(_owner);
emit OwnerChanged(msg.sender, _owner);
}
/// @notice Allows owner to set a new price for 1 token
/// @dev uint64 is 18,446,744,073,709,551,615 which seems like an expensive stay at our BNB
function changeTokenPrice(uint64 _newPrice) public onlyOwner {
require(_newPrice > 0, "New price must be more than zero");
// emit an event w/ new and old values
emit TokenPriceChanged(bookingTokenPrice, _newPrice);
//check if msg.sender have minter role
bookingTokenPrice = _newPrice;
}
/// @notice Returns the price of ETH / USD from Chainlink Rinkeby price feed
/// @dev Chainlink returns int256 values which can be negative
/// @return int256
function returnPrice() internal view returns (int256) {
// not for production; suggest you revert, call propietary fallback oracle, fetch from another 3rd-party oracle, etc.
// in our case lets just return 1 eth === 1000 USD
// ETH won't fall under $1000, right? ....right?
int256 fallbackValue = 1000 * 1e8;
if (useFixedPricing) {
return fallbackValue;
}
try priceFeed.latestRoundData() returns (
uint80,
int256 price,
uint256,
uint256,
uint80
) {
return price;
} catch Error(string memory _err) {
console.log(_err);
return fallbackValue;
}
}
/// @notice Returns the price of X tokens
/// @dev Chainlink returns int256 values which can be negative; converted to uint in this function
/// @return uint256
function getEthPriceForTokens(uint256 _numTokens)
public
view
returns (uint256)
{
require(_numTokens > 0, "invalid number of tokens");
// get the raw int256 price
int256 rawEthToUsdPrice = returnPrice();
// protect against overflows from the priceFeed since int can be negative
require(rawEthToUsdPrice >= 0, "price for Ether cannot be negative");
// convert it to uint so we can compare to msg.value
uint256 ethToUsdPrice = uint256(rawEthToUsdPrice);
// USDC needs 8 decimals added
uint256 normalizedPrice = ethToUsdPrice.div(1e8);
// get the price for 1 token
uint256 priceFor1Token = (bookingTokenPrice.mul(1e18)).div(
normalizedPrice
);
// and then multiply that price by _numTokens and then by 1e18 which converts eth to wei
return priceFor1Token.mul(_numTokens);
}
/// @notice Allows user to buy a X tokens
/// @dev msg.value must be >= the getEthPriceForTokens value
function buyTokens(uint256 _numTokens) public payable {
require(msg.value > 0, "must send ether in request");
uint256 etherPrice = getEthPriceForTokens(_numTokens);
require(msg.value >= etherPrice, "not enough ether sent in request");
// transfers ETH to owner account
(bool sent, ) = owner.call{value: msg.value}("");
require(sent, "Failed to send Ether");
bookingToken.mint(msg.sender, _numTokens);
// use bookingTokenPrice for easy human-readable USD value
emit TokenBought(msg.sender, _numTokens, bookingTokenPrice);
}
}
| @notice Shortcut to return balanceOf a given address from our token contract @dev you can just call the bookingToken function directly once you know the address; I set it to private and just included this function since its all thats relevant to our example @return uint256 | function getTokenBalance(address _address) public view returns (uint256) {
return bookingToken.balanceOf(_address);
}
| 5,532,971 | [
1,
15576,
358,
327,
11013,
951,
279,
864,
1758,
628,
3134,
1147,
6835,
225,
1846,
848,
2537,
745,
326,
6978,
310,
1345,
445,
5122,
3647,
1846,
5055,
326,
1758,
31,
467,
444,
518,
358,
3238,
471,
2537,
5849,
333,
445,
3241,
2097,
777,
716,
87,
9368,
358,
3134,
3454,
327,
2254,
5034,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9162,
13937,
12,
2867,
389,
2867,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
6978,
310,
1345,
18,
12296,
951,
24899,
2867,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0xE30E68313e691F7A652c775cb88BBFBB131863bf/sources/Validators.sol | do nothing if validator not exist(impossible) for display purpose | function tryRemoveValidatorIncoming(address val) private {
if (
validatorInfo[val].status == Status.NotExist ||
currentValidatorSet.length <= 1
) {
return;
}
uint256 hb = validatorInfo[val].hbIncoming;
if (hb > 0) {
addProfitsToActiveValidatorsByStakePercentExcept(hb, val);
totalJailedHB = totalJailedHB + (hb);
validatorInfo[val].totalJailedHB = validatorInfo[val]
.totalJailedHB
+ (hb);
validatorInfo[val].hbIncoming = 0;
}
emit LogRemoveValidatorIncoming(val, hb, block.timestamp);
}
| 5,017,764 | [
1,
2896,
5083,
309,
4213,
486,
1005,
12,
381,
12708,
13,
364,
2562,
13115,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
775,
3288,
5126,
20370,
12,
2867,
1244,
13,
3238,
288,
203,
3639,
309,
261,
203,
5411,
4213,
966,
63,
1125,
8009,
2327,
422,
2685,
18,
8418,
747,
203,
5411,
783,
5126,
694,
18,
2469,
1648,
404,
203,
3639,
262,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
21749,
273,
4213,
966,
63,
1125,
8009,
76,
70,
20370,
31,
203,
3639,
309,
261,
76,
70,
405,
374,
13,
288,
203,
5411,
527,
626,
18352,
774,
3896,
19420,
858,
510,
911,
8410,
30212,
12,
76,
70,
16,
1244,
1769,
203,
5411,
2078,
46,
1708,
44,
38,
273,
2078,
46,
1708,
44,
38,
397,
261,
76,
70,
1769,
203,
5411,
4213,
966,
63,
1125,
8009,
4963,
46,
1708,
44,
38,
273,
4213,
966,
63,
1125,
65,
203,
7734,
263,
4963,
46,
1708,
44,
38,
203,
7734,
397,
261,
76,
70,
1769,
203,
203,
5411,
4213,
966,
63,
1125,
8009,
76,
70,
20370,
273,
374,
31,
203,
3639,
289,
203,
203,
3639,
3626,
1827,
3288,
5126,
20370,
12,
1125,
16,
21749,
16,
1203,
18,
5508,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42220/0xB23e54fd8c2f35F9d38884Fc1611F5e9004f10ea/sources/project_/contracts/utils/OneTimePayments.sol | @dev Withdrawal function. allows the sender that proves ownership of paymentId to withdraw @param paymentId the address of the public key that the rightful receiver of the payment knows the private key to @param signature the signature of a the message containing the msg.sender address signed with the private key./ | function withdraw(address paymentId, bytes memory signature) public {
address signer = signerOfAddress(msg.sender, signature);
require(signer == paymentId, "Signature is not correct");
uint256 value = payments[paymentId].paymentAmount;
address sender = payments[paymentId].paymentSender;
_withdraw(paymentId, value);
emit PaymentWithdraw(sender, msg.sender, paymentId, value);
}
| 3,496,034 | [
1,
1190,
9446,
287,
445,
18,
5360,
326,
5793,
716,
450,
3324,
23178,
434,
5184,
548,
358,
598,
9446,
225,
5184,
548,
326,
1758,
434,
326,
1071,
498,
716,
326,
282,
2145,
2706,
5971,
434,
326,
5184,
21739,
326,
3238,
498,
358,
225,
3372,
326,
3372,
434,
279,
326,
883,
4191,
326,
1234,
18,
15330,
1758,
6726,
282,
598,
326,
3238,
498,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
598,
9446,
12,
2867,
5184,
548,
16,
1731,
3778,
3372,
13,
1071,
288,
203,
202,
202,
2867,
10363,
273,
10363,
951,
1887,
12,
3576,
18,
15330,
16,
3372,
1769,
203,
202,
202,
6528,
12,
2977,
264,
422,
5184,
548,
16,
315,
5374,
353,
486,
3434,
8863,
203,
203,
202,
202,
11890,
5034,
460,
273,
25754,
63,
9261,
548,
8009,
9261,
6275,
31,
203,
202,
202,
2867,
5793,
273,
25754,
63,
9261,
548,
8009,
9261,
12021,
31,
203,
203,
202,
202,
67,
1918,
9446,
12,
9261,
548,
16,
460,
1769,
203,
202,
202,
18356,
12022,
1190,
9446,
12,
15330,
16,
1234,
18,
15330,
16,
5184,
548,
16,
460,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x8eb965ee9ccfbce76c0a06264492c0afefc2826d
//Contract name: ToorToken
//Balance: 0 Ether
//Verification Date: 6/13/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title 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) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
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) {
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;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract ToorToken is ERC20Basic, Ownable {
using SafeMath for uint256;
struct Account {
uint balance;
uint lastInterval;
}
mapping(address => Account) public accounts;
mapping(uint256 => uint256) ratesByYear;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 private rateMultiplier;
uint256 initialSupply_;
uint256 totalSupply_;
uint256 public maxSupply;
uint256 public startTime;
uint256 public pendingRewardsToMint;
string public name;
uint public decimals;
string public symbol;
uint256 private tokenGenInterval; // This defines the frequency at which we calculate rewards
uint256 private vestingPeriod; // Defines how often tokens vest to team
uint256 private cliff; // Defines the minimum amount of time required before tokens vest
uint256 public pendingInstallments; // Defines the number of pending vesting installments for team
uint256 public paidInstallments; // Defines the number of paid vesting installments for team
uint256 private totalVestingPool; // Defines total vesting pool set aside for team
uint256 public pendingVestingPool; // Defines pending tokens in pool set aside for team
uint256 public finalIntervalForTokenGen; // The last instance of reward calculation, after which rewards will cease
uint256 private totalRateWindows; // This specifies the number of rate windows over the total period of time
uint256 private intervalsPerWindow; // Total number of times we calculate rewards within 1 rate window
// Variable to define once reward generation is complete
bool public rewardGenerationComplete;
// Ether addresses of founders and company
mapping(uint256 => address) public distributionAddresses;
// Events section
event Mint(address indexed to, uint256 amount);
event Burn(address indexed burner, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function ToorToken() public {
name = "ToorCoin";
decimals = 18;
symbol = "TOOR";
// Setup the token staking reward percentage per year
rateMultiplier = 10**9;
ratesByYear[1] = 1.00474436 * 10**9;
ratesByYear[2] = 1.003278088 * 10**9;
ratesByYear[3] = 1.002799842 * 10**9;
ratesByYear[4] = 1.002443535 * 10**9;
ratesByYear[5] = 1.002167763 * 10**9;
ratesByYear[6] = 1.001947972 * 10**9;
ratesByYear[7] = 1.001768676 * 10**9;
ratesByYear[8] = 1.001619621 * 10**9;
ratesByYear[9] = 1.001493749 * 10**9;
ratesByYear[10] = 1.001386038 * 10**9;
ratesByYear[11] = 1.001292822 * 10**9;
ratesByYear[12] = 1.001211358 * 10**9;
ratesByYear[13] = 1.001139554 * 10**9;
ratesByYear[14] = 1.001075789 * 10**9;
ratesByYear[15] = 1.001018783 * 10**9;
ratesByYear[16] = 1.000967516 * 10**9;
ratesByYear[17] = 1.000921162 * 10**9;
ratesByYear[18] = 1.000879048 * 10**9;
ratesByYear[19] = 1.000840616 * 10**9;
ratesByYear[20] = 1.000805405 * 10**9;
totalRateWindows = 20;
maxSupply = 100000000 * 10**18;
initialSupply_ = 13500000 * 10**18;
pendingInstallments = 7;
paidInstallments = 0;
totalVestingPool = 4500000 * 10**18;
startTime = now;
distributionAddresses[1] = 0x7d3BC9bb69dAB0544d34b7302DED8806bCF715e6; // founder 1
distributionAddresses[2] = 0x34Cf9afae3f926B9D040CA7A279C411355c5C480; // founder 2
distributionAddresses[3] = 0x059Cbd8A57b1dD944Da020a0D0a18D8dD7e78E04; // founder 3
distributionAddresses[4] = 0x4F8bC705827Fb8A781b27B9F02d2491F531f8962; // founder 4
distributionAddresses[5] = 0x532d370a98a478714625E9148D1205be061Df3bf; // founder 5
distributionAddresses[6] = 0xDe485bB000fA57e73197eF709960Fb7e32e0380E; // company
distributionAddresses[7] = 0xd562f635c75D2d7f3BE0005FBd3808a5cfb896bd; // bounty
// This is for 20 years
tokenGenInterval = 603936; // This is roughly 1 week in seconds
uint256 timeToGenAllTokens = 628093440; // This is close to 20 years in seconds
rewardGenerationComplete = false;
// Mint initial tokens
accounts[distributionAddresses[6]].balance = (initialSupply_ * 60) / 100; // 60% of initial balance goes to Company
accounts[distributionAddresses[6]].lastInterval = 0;
generateMintEvents(distributionAddresses[6],accounts[distributionAddresses[6]].balance);
accounts[distributionAddresses[7]].balance = (initialSupply_ * 40) / 100; // 40% of inital balance goes to Bounty
accounts[distributionAddresses[7]].lastInterval = 0;
generateMintEvents(distributionAddresses[7],accounts[distributionAddresses[7]].balance);
pendingVestingPool = totalVestingPool;
pendingRewardsToMint = maxSupply - initialSupply_ - totalVestingPool;
totalSupply_ = initialSupply_;
vestingPeriod = timeToGenAllTokens / (totalRateWindows * 12); // One vesting period is a month
cliff = vestingPeriod * 6; // Cliff is six vesting periods aka 6 months roughly
finalIntervalForTokenGen = timeToGenAllTokens / tokenGenInterval;
intervalsPerWindow = finalIntervalForTokenGen / totalRateWindows;
}
// This gives the total supply of actual minted coins. Does not take rewards pending minting into consideration
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
// This function is called directly by users who wish to transfer tokens
function transfer(address _to, uint256 _value) canTransfer(_to) public returns (bool) {
// Call underlying transfer method and pass in the sender address
transferBasic(msg.sender, _to, _value);
return true;
}
// This function is called by both transfer and transferFrom
function transferBasic(address _from, address _to, uint256 _value) internal {
uint256 tokensOwedSender = 0;
uint256 tokensOwedReceiver = 0;
uint256 balSender = balanceOfBasic(_from);
// Distribute rewards tokens first
if (!rewardGenerationComplete) {
tokensOwedSender = tokensOwed(_from);
require(_value <= (balSender.add(tokensOwedSender))); // Sender should have the number of tokens they want to send
tokensOwedReceiver = tokensOwed(_to);
// If there were tokens owed, increase total supply accordingly
if ((tokensOwedSender.add(tokensOwedReceiver)) > 0) {
increaseTotalSupply(tokensOwedSender.add(tokensOwedReceiver)); // This will break if total exceeds max cap
pendingRewardsToMint = pendingRewardsToMint.sub(tokensOwedSender.add(tokensOwedReceiver));
}
// If there were tokens owed, raise mint events for them
raiseEventIfMinted(_from, tokensOwedSender);
raiseEventIfMinted(_to, tokensOwedReceiver);
} else {
require(_value <= balSender);
}
// Update balances of sender and receiver
accounts[_from].balance = (balSender.add(tokensOwedSender)).sub(_value);
accounts[_to].balance = (accounts[_to].balance.add(tokensOwedReceiver)).add(_value);
// Update last intervals for sender and receiver
uint256 currInt = intervalAtTime(now);
accounts[_from].lastInterval = currInt;
accounts[_to].lastInterval = currInt;
emit Transfer(_from, _to, _value);
}
// If you want to transfer tokens to multiple receivers at once
function batchTransfer(address[] _receivers, uint256 _value) public returns (bool) {
uint256 cnt = _receivers.length;
uint256 amount = cnt.mul(_value);
// Check that the value to send is more than 0
require(_value > 0);
// Add pending rewards for sender first
if (!rewardGenerationComplete) {
addReward(msg.sender);
}
// Get current balance of sender
uint256 balSender = balanceOfBasic(msg.sender);
// Check that the sender has the required amount
require(balSender >= amount);
// Update balance and lastInterval of sender
accounts[msg.sender].balance = balSender.sub(amount);
uint256 currInt = intervalAtTime(now);
accounts[msg.sender].lastInterval = currInt;
for (uint i = 0; i < cnt; i++) {
// Add pending rewards for receiver first
if (!rewardGenerationComplete) {
address receiver = _receivers[i];
addReward(receiver);
}
// Update balance and lastInterval of receiver
accounts[_receivers[i]].balance = (accounts[_receivers[i]].balance).add(_value);
accounts[_receivers[i]].lastInterval = currInt;
emit Transfer(msg.sender, _receivers[i], _value);
}
return true;
}
// This function allows someone to withdraw tokens from someone's address
// For this to work, the person needs to have been approved by the account owner (via the approve function)
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_to) public returns (bool)
{
// Check that function caller has been approved to withdraw tokens
require(_value <= allowed[_from][msg.sender]);
// Call out base transfer method
transferBasic(_from, _to, _value);
// Subtract withdrawn tokens from allowance
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256)
{
return allowed[_owner][_spender];
}
// Increase the amount of tokens that an owner allowed to a spender.
// approve should be called when allowed[_spender] == 0. To increment
// allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
function increaseApproval(address _spender, uint _addedValue) public returns (bool)
{
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// Decrease the amount of tokens that an owner allowed to a spender.
// approve should be called when allowed[_spender] == 0. To decrement
// allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function raiseEventIfMinted(address owner, uint256 tokensToReward) private returns (bool) {
if (tokensToReward > 0) {
generateMintEvents(owner, tokensToReward);
}
}
function addReward(address owner) private returns (bool) {
uint256 tokensToReward = tokensOwed(owner);
if (tokensToReward > 0) {
increaseTotalSupply(tokensToReward); // This will break if total supply exceeds max cap. Should never happen though as tokensOwed checks for this condition
accounts[owner].balance = accounts[owner].balance.add(tokensToReward);
accounts[owner].lastInterval = intervalAtTime(now);
pendingRewardsToMint = pendingRewardsToMint.sub(tokensToReward); // This helps track rounding errors when computing rewards
generateMintEvents(owner, tokensToReward);
}
return true;
}
// This function is to vest tokens to the founding team
// This deliberately doesn't use SafeMath as all the values are controlled without risk of overflow
function vestTokens() public returns (bool) {
require(pendingInstallments > 0);
require(paidInstallments < 7);
require(pendingVestingPool > 0);
require(now - startTime > cliff);
// If they have rewards pending, allocate those first
if (!rewardGenerationComplete) {
for (uint256 i = 1; i <= 5; i++) {
addReward(distributionAddresses[i]);
}
}
uint256 currInterval = intervalAtTime(now);
uint256 tokensToVest = 0;
uint256 totalTokensToVest = 0;
uint256 totalPool = totalVestingPool;
uint256[2] memory founderCat;
founderCat[0] = 0;
founderCat[1] = 0;
uint256[5] memory origFounderBal;
origFounderBal[0] = accounts[distributionAddresses[1]].balance;
origFounderBal[1] = accounts[distributionAddresses[2]].balance;
origFounderBal[2] = accounts[distributionAddresses[3]].balance;
origFounderBal[3] = accounts[distributionAddresses[4]].balance;
origFounderBal[4] = accounts[distributionAddresses[5]].balance;
uint256[2] memory rewardCat;
rewardCat[0] = 0;
rewardCat[1] = 0;
// Pay out cliff
if (paidInstallments < 1) {
uint256 intervalAtCliff = intervalAtTime(cliff + startTime);
tokensToVest = totalPool / 4;
founderCat[0] = tokensToVest / 4;
founderCat[1] = tokensToVest / 8;
// Update vesting pool
pendingVestingPool -= tokensToVest;
// This condition checks if there are any rewards to pay after the cliff
if (currInterval > intervalAtCliff && !rewardGenerationComplete) {
rewardCat[0] = tokensOwedByInterval(founderCat[0], intervalAtCliff, currInterval);
rewardCat[1] = rewardCat[0] / 2;
// Add rewards to founder tokens being vested
founderCat[0] += rewardCat[0];
founderCat[1] += rewardCat[1];
// Increase total amount of tokens to vest
tokensToVest += ((3 * rewardCat[0]) + (2 * rewardCat[1]));
// Reduce pending rewards
pendingRewardsToMint -= ((3 * rewardCat[0]) + (2 * rewardCat[1]));
}
// Vest tokens for each of the founders, this includes any rewards pending since cliff passed
accounts[distributionAddresses[1]].balance += founderCat[0];
accounts[distributionAddresses[2]].balance += founderCat[0];
accounts[distributionAddresses[3]].balance += founderCat[0];
accounts[distributionAddresses[4]].balance += founderCat[1];
accounts[distributionAddresses[5]].balance += founderCat[1];
totalTokensToVest = tokensToVest;
// Update pending and paid installments
pendingInstallments -= 1;
paidInstallments += 1;
}
// Calculate the pending non-cliff installments to pay based on current time
uint256 installments = ((currInterval * tokenGenInterval) - cliff) / vestingPeriod;
uint256 installmentsToPay = installments + 1 - paidInstallments;
// If there are no installments to pay, skip this
if (installmentsToPay > 0) {
if (installmentsToPay > pendingInstallments) {
installmentsToPay = pendingInstallments;
}
// 12.5% vesting monthly after the cliff
tokensToVest = (totalPool * 125) / 1000;
founderCat[0] = tokensToVest / 4;
founderCat[1] = tokensToVest / 8;
uint256 intervalsAtVest = 0;
// Loop through installments to pay, so that we can add token holding rewards as we go along
for (uint256 installment = paidInstallments; installment < (installmentsToPay + paidInstallments); installment++) {
intervalsAtVest = intervalAtTime(cliff + (installment * vestingPeriod) + startTime);
// This condition checks if there are any rewards to pay after the cliff
if (currInterval >= intervalsAtVest && !rewardGenerationComplete) {
rewardCat[0] = tokensOwedByInterval(founderCat[0], intervalsAtVest, currInterval);
rewardCat[1] = rewardCat[0] / 2;
// Increase total amount of tokens to vest
totalTokensToVest += tokensToVest;
totalTokensToVest += ((3 * rewardCat[0]) + (2 * rewardCat[1]));
// Reduce pending rewards
pendingRewardsToMint -= ((3 * rewardCat[0]) + (2 * rewardCat[1]));
// Vest tokens for each of the founders, this includes any rewards pending since vest interval passed
accounts[distributionAddresses[1]].balance += (founderCat[0] + rewardCat[0]);
accounts[distributionAddresses[2]].balance += (founderCat[0] + rewardCat[0]);
accounts[distributionAddresses[3]].balance += (founderCat[0] + rewardCat[0]);
accounts[distributionAddresses[4]].balance += (founderCat[1] + rewardCat[1]);
accounts[distributionAddresses[5]].balance += (founderCat[1] + rewardCat[1]);
}
}
// Reduce pendingVestingPool and update pending and paid installments
pendingVestingPool -= (installmentsToPay * tokensToVest);
pendingInstallments -= installmentsToPay;
paidInstallments += installmentsToPay;
}
// Increase total supply by the number of tokens being vested
increaseTotalSupply(totalTokensToVest);
accounts[distributionAddresses[1]].lastInterval = currInterval;
accounts[distributionAddresses[2]].lastInterval = currInterval;
accounts[distributionAddresses[3]].lastInterval = currInterval;
accounts[distributionAddresses[4]].lastInterval = currInterval;
accounts[distributionAddresses[5]].lastInterval = currInterval;
// Create events for token generation
generateMintEvents(distributionAddresses[1], (accounts[distributionAddresses[1]].balance - origFounderBal[0]));
generateMintEvents(distributionAddresses[2], (accounts[distributionAddresses[2]].balance - origFounderBal[1]));
generateMintEvents(distributionAddresses[3], (accounts[distributionAddresses[3]].balance - origFounderBal[2]));
generateMintEvents(distributionAddresses[4], (accounts[distributionAddresses[4]].balance - origFounderBal[3]));
generateMintEvents(distributionAddresses[5], (accounts[distributionAddresses[5]].balance - origFounderBal[4]));
}
function increaseTotalSupply (uint256 tokens) private returns (bool) {
require ((totalSupply_.add(tokens)) <= maxSupply);
totalSupply_ = totalSupply_.add(tokens);
return true;
}
function tokensOwed(address owner) public view returns (uint256) {
// This array is introduced to circumvent stack depth issues
uint256 currInterval = intervalAtTime(now);
uint256 lastInterval = accounts[owner].lastInterval;
uint256 balance = accounts[owner].balance;
return tokensOwedByInterval(balance, lastInterval, currInterval);
}
function tokensOwedByInterval(uint256 balance, uint256 lastInterval, uint256 currInterval) public view returns (uint256) {
// Once the specified address has received all possible rewards, don't calculate anything
if (lastInterval >= currInterval || lastInterval >= finalIntervalForTokenGen) {
return 0;
}
uint256 tokensHeld = balance; //tokensHeld
uint256 intPerWin = intervalsPerWindow;
uint256 totalRateWinds = totalRateWindows;
// Defines the number of intervals we compute rewards for at a time
uint256 intPerBatch = 5; // Hardcoded here instead of storing on blockchain to save gas
mapping(uint256 => uint256) ratByYear = ratesByYear;
uint256 ratMultiplier = rateMultiplier;
uint256 minRateWindow = (lastInterval / intPerWin).add(1);
uint256 maxRateWindow = (currInterval / intPerWin).add(1);
if (maxRateWindow > totalRateWinds) {
maxRateWindow = totalRateWinds;
}
// Loop through pending periods of rewards, and calculate the total balance user should hold
for (uint256 rateWindow = minRateWindow; rateWindow <= maxRateWindow; rateWindow++) {
uint256 intervals = getIntervalsForWindow(rateWindow, lastInterval, currInterval, intPerWin);
// This part is to ensure we don't overflow when rewards are pending for a large number of intervals
// Loop through interval in batches
while (intervals > 0) {
if (intervals >= intPerBatch) {
tokensHeld = (tokensHeld.mul(ratByYear[rateWindow] ** intPerBatch)) / (ratMultiplier ** intPerBatch);
intervals = intervals.sub(intPerBatch);
} else {
tokensHeld = (tokensHeld.mul(ratByYear[rateWindow] ** intervals)) / (ratMultiplier ** intervals);
intervals = 0;
}
}
}
// Rewards owed are the total balance that user SHOULD have minus what they currently have
return (tokensHeld.sub(balance));
}
function intervalAtTime(uint256 time) public view returns (uint256) {
// Check to see that time passed in is not before contract generation time, as that would cause a negative value in the next step
if (time <= startTime) {
return 0;
}
// Based on time passed in, check how many intervals have elapsed
uint256 interval = (time.sub(startTime)) / tokenGenInterval;
uint256 finalInt = finalIntervalForTokenGen; // Assign to local to reduce gas
// Return max intervals if it's greater than that time
if (interval > finalInt) {
return finalInt;
} else {
return interval;
}
}
// This function checks how many intervals for a given window do we owe tokens to someone for
function getIntervalsForWindow(uint256 rateWindow, uint256 lastInterval, uint256 currInterval, uint256 intPerWind) public pure returns (uint256) {
// If lastInterval for holder falls in a window previous to current one, the lastInterval for the window passed into the function would be the window start interval
if (lastInterval < ((rateWindow.sub(1)).mul(intPerWind))) {
lastInterval = ((rateWindow.sub(1)).mul(intPerWind));
}
// If currentInterval for holder falls in a window higher than current one, the currentInterval for the window passed into the function would be the window end interval
if (currInterval > rateWindow.mul(intPerWind)) {
currInterval = rateWindow.mul(intPerWind);
}
return currInterval.sub(lastInterval);
}
// This function tells the balance of tokens at a particular address
function balanceOf(address _owner) public view returns (uint256 balance) {
if (rewardGenerationComplete) {
return accounts[_owner].balance;
} else {
return (accounts[_owner].balance).add(tokensOwed(_owner));
}
}
function balanceOfBasic(address _owner) public view returns (uint256 balance) {
return accounts[_owner].balance;
}
// This functions returns the last time at which rewards were transferred to a particular address
function lastTimeOf(address _owner) public view returns (uint256 interval, uint256 time) {
return (accounts[_owner].lastInterval, ((accounts[_owner].lastInterval).mul(tokenGenInterval)).add(startTime));
}
// This function is not meant to be used. It's only written as a fail-safe against potential unforeseen issues
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
// Add pending rewards for recipient of minted tokens
if (!rewardGenerationComplete) {
addReward(_to);
}
// Increase total supply by minted amount
increaseTotalSupply(_amount);
// Update balance and last interval
accounts[_to].lastInterval = intervalAtTime(now);
accounts[_to].balance = (accounts[_to].balance).add(_amount);
generateMintEvents(_to, _amount);
return true;
}
function generateMintEvents(address _to, uint256 _amount) private returns (bool) {
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
// Allows the burning of tokens
function burn(uint256 _value) public {
require(_value <= balanceOf(msg.sender));
// First add any rewards pending for the person burning tokens
if (!rewardGenerationComplete) {
addReward(msg.sender);
}
// Update balance and lastInterval of person burning tokens
accounts[msg.sender].balance = (accounts[msg.sender].balance).sub(_value);
accounts[msg.sender].lastInterval = intervalAtTime(now);
// Update total supply
totalSupply_ = totalSupply_.sub(_value);
// Raise events
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
// These set of functions allow changing of founder and company addresses
function setFounder(uint256 id, address _to) onlyOwner public returns (bool) {
require(_to != address(0));
distributionAddresses[id] = _to;
return true;
}
// This is a setter for rewardGenerationComplete. It will be used to see if token rewards need to be computed, and can only be set by owner
function setRewardGenerationComplete(bool _value) onlyOwner public returns (bool) {
rewardGenerationComplete = _value;
return true;
}
// This function is added to get a state of where the token is in term of reward generation
function getNow() public view returns (uint256, uint256, uint256) {
return (now, block.number, intervalAtTime(now));
}
// This modifier is used on the transfer method and defines where tokens CANNOT be sent
modifier canTransfer(address _to) {
require(_to != address(0)); // Transfer should not be allowed to burn tokens
_;
}
}
| This function allows someone to withdraw tokens from someone's address For this to work, the person needs to have been approved by the account owner (via the approve function) Check that function caller has been approved to withdraw tokens Call out base transfer method Subtract withdrawn tokens from allowance | function transferFrom(address _from, address _to, uint256 _value) canTransfer(_to) public returns (bool)
{
require(_value <= allowed[_from][msg.sender]);
transferBasic(_from, _to, _value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
return true;
}
| 1,005,523 | [
1,
2503,
445,
5360,
18626,
358,
598,
9446,
2430,
628,
18626,
1807,
1758,
2457,
333,
358,
1440,
16,
326,
6175,
4260,
358,
1240,
2118,
20412,
635,
326,
2236,
3410,
261,
21985,
326,
6617,
537,
445,
13,
2073,
716,
445,
4894,
711,
2118,
20412,
358,
598,
9446,
2430,
3049,
596,
1026,
7412,
707,
2592,
1575,
598,
9446,
82,
2430,
628,
1699,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
848,
5912,
24899,
869,
13,
1071,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
24899,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
19226,
203,
203,
3639,
7412,
8252,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
203,
3639,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
// import '@nomiclabs/buidler/console.sol';
import "./ERC1155.sol";
import "./IERC1155Views.sol";
contract TokensFlow is ERC1155, IERC1155Views {
using SafeMath for uint256;
using Address for address;
// See also _createSwapLimit()
struct SwapLimit {
bool recurring;
int256 initialSwapCredit;
int256 maxSwapCredit;
int swapCreditPeriod;
int firstTimeEnteredSwapCredit;
bytes32 hash;
}
struct TokenFlow {
uint256 parentToken;
SwapLimit limit;
int256 remainingSwapCredit;
int timeEnteredSwapCredit; // zero means not in a swap credit
int lastSwapTime; // ignored when not in a swap credit
bool enabled;
}
uint256 public maxTokenId;
mapping (uint256 => address) public tokenOwners;
mapping (uint256 => TokenFlow) public tokenFlow;
// IERC1155Views
mapping (uint256 => uint256) private totalSupplyImpl;
mapping (uint256 => string) private nameImpl;
mapping (uint256 => string) private symbolImpl;
mapping (uint256 => string) private uriImpl;
function totalSupply(uint256 _id) external override view returns (uint256) {
return totalSupplyImpl[_id];
}
function name(uint256 _id) external override view returns (string memory) {
return nameImpl[_id];
}
function symbol(uint256 _id) external override view returns (string memory) {
return symbolImpl[_id];
}
function decimals(uint256) external override pure returns (uint8) {
return 18;
}
function uri(uint256 _id) external override view returns (string memory) {
return uriImpl[_id];
}
// Administrativia
function newToken(uint256 _parent, string calldata _name, string calldata _symbol, string calldata _uri)
external returns (uint256)
{
return _newToken(_parent, _name, _symbol, _uri, msg.sender);
}
function setTokenOwner(uint256 _id, address _newOwner) external {
require(msg.sender == tokenOwners[_id]);
require(_id != 0);
tokenOwners[_id] = _newOwner;
}
function removeTokenOwner(uint256 _id) external {
require(msg.sender == tokenOwners[_id]);
tokenOwners[_id] = address(0);
}
// Intentially no setTokenName() and setTokenSymbol()
function setTokenUri(uint256 _id, string calldata _uri) external {
require(msg.sender == tokenOwners[_id]);
uriImpl[_id] = _uri;
}
// We don't check for circularities.
function setTokenParent(uint256 _child, uint256 _parent) external {
// require(_child != 0 && _child <= maxTokenId); // not needed
require(msg.sender == tokenOwners[_child]);
_setTokenParentNoCheck(_child, _parent);
}
// Each element of `_childs` list must be a child of the next one.
// TODO: Test. Especially test the case if the last child has no parent. Also test if a child is zero.
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint256 _firstChild = _childs[0]; // asserts on `_childs.length == 0`.
bool _hasRight = false; // if msg.sender is an ancestor
// Note that if in the below loops we disable ourselves, then it will be detected by a require
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
// We are not msg.sender
tokenFlow[_id].enabled = _enabled; // cannot enable for msg.sender
++i;
}
require(_hasRight);
}
// User can set negative values. It is a nonsense but does not harm.
function setRecurringFlow(
uint256 _child,
int256 _maxSwapCredit,
int256 _remainingSwapCredit,
int _swapCreditPeriod, int _timeEnteredSwapCredit,
bytes32 oldLimitHash) external
{
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
require(_flow.limit.hash == oldLimitHash);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
_flow.limit = _createSwapLimit(true, _remainingSwapCredit, _maxSwapCredit, _swapCreditPeriod, _timeEnteredSwapCredit);
_flow.timeEnteredSwapCredit = _timeEnteredSwapCredit;
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// User can set negative values. It is a nonsense but does not harm.
function setNonRecurringFlow(uint256 _child, int256 _remainingSwapCredit, bytes32 oldLimitHash) external {
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
require(_flow.limit.hash == oldLimitHash);
_flow.limit = _createSwapLimit(false, _remainingSwapCredit, 0, 0, 0);
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// ERC-1155
// A token can anyway change its parent at any moment, so disabling of payments makes no sense.
// function safeTransferFrom(
// address _from,
// address _to,
// uint256 _id,
// uint256 _value,
// bytes calldata _data) external virtual override
// {
// require(tokenFlow[_id].enabled);
// super._safeTransferFrom(_from, _to, _id, _value, _data);
// }
// function safeBatchTransferFrom(
// address _from,
// address _to,
// uint256[] calldata _ids,
// uint256[] calldata _values,
// bytes calldata _data) external virtual override
// {
// for (uint i = 0; i < _ids.length; ++i) {
// require(tokenFlow[_ids[i]].enabled);
// }
// super._safeBatchTransferFrom(_from, _to, _ids, _values, _data);
// }
// Misc
function burn(address _from, uint256 _id, uint256 _value) external {
require(_from == msg.sender || operatorApproval[msg.sender][_from], "No approval.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check overflow due to previous line
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Flow
// Each next token ID must be a parent of the previous one.
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
// Intentionally no check for `msg.sender`.
require(_ids[_ids.length - 1] != 0); // The rest elements are checked below.
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
require(_parent == _ids[i + 1]); // i ranges 0 .. _ids.length - 2
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
} else {
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
_flow.lastSwapTime = _currentTimeResult; // TODO: no strictly necessary if !_flow.recurring
// require(_amount < 1<<128); // done above
_flow.remainingSwapCredit -= int256(_amount);
}
// if (_id == _flow.parentToken) return; // not necessary
_doBurn(msg.sender, _ids[0], _amount);
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
// Each next token ID must be a parent of the previous one.
function exchangeToDescendant(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
uint256 _parent = _ids[0];
require(_parent != 0);
for(uint i = 1; i != _ids.length; ++i) {
_parent = tokenFlow[_parent].parentToken;
require(_parent != 0);
require(_parent == _ids[i]); // consequently `_ids[i] != 0`
}
_doBurn(msg.sender, _ids[_ids.length - 1], _amount);
_doMint(msg.sender, _ids[0], _amount, _data);
}
// Internal
function _newToken(
uint256 _parent,
string memory _name, string memory _symbol, string memory _uri,
address _owner) internal returns (uint256)
{
tokenOwners[++maxTokenId] = _owner;
nameImpl[maxTokenId] = _name;
symbolImpl[maxTokenId] = _symbol;
uriImpl[maxTokenId] = _uri;
_setTokenParentNoCheck(maxTokenId, _parent);
emit NewToken(maxTokenId, _owner, _name, _symbol, _uri);
return maxTokenId;
}
function _doMint(address _to, uint256 _id, uint256 _value, bytes memory _data) public {
require(_to != address(0), "_to must be non-zero.");
if (_value != 0) {
totalSupplyImpl[_id] = _value.add(totalSupplyImpl[_id]);
balances[_id][_to] += _value; // no need to check for overflow due to the previous line
}
// MUST emit event
emit TransferSingle(msg.sender, address(0), _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, address(0), _to, _id, _value, _data);
}
}
function _doBurn(address _from, uint256 _id, uint256 _value) public {
// require(_from != address(0), "_from must be non-zero.");
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check for overflow due to the previous line
// MUST emit event
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Also resets swap credits and `enabled`, so use with caution.
// Allow this even if `!enabled` and set `enabled` to `true` if no parent,
// as otherwise impossible to enable it again.
function _setTokenParentNoCheck(uint256 _child, uint256 _parent) internal virtual {
require(_parent <= maxTokenId);
tokenFlow[_child] = TokenFlow({
parentToken: _parent,
limit: _createSwapLimit(false, 0, 0, 0, 0),
timeEnteredSwapCredit: 0, // zero means not in a swap credit
lastSwapTime: 0,
remainingSwapCredit: 0,
enabled: _parent == 0
});
}
function _currentTime() internal virtual view returns(int) {
return int(block.timestamp);
}
function _inSwapCredit(TokenFlow memory _flow, int _currentTimeResult) public pure returns(bool) {
// solhint-disable indent
return _flow.timeEnteredSwapCredit != 0 &&
_currentTimeResult - _flow.timeEnteredSwapCredit < _flow.limit.swapCreditPeriod;
}
function _maxRecurringSwapAmount(TokenFlow memory _flow, int _currentTimeResult, bool _inSwapCreditResult)
public pure returns(uint256)
{
int256 result;
if (_inSwapCreditResult) {
int256 passedTime = _currentTimeResult - _flow.lastSwapTime;
int256 delta = _flow.limit.maxSwapCredit * passedTime / _flow.limit.swapCreditPeriod;
result = _flow.remainingSwapCredit - delta;
} else {
result = _flow.limit.maxSwapCredit;
}
return result < 0 ? 0 : uint256(result);
}
function _createSwapLimit(
bool _recurring,
int256 _initialSwapCredit,
int256 _maxSwapCredit,
int _swapCreditPeriod,
int _firstTimeEnteredSwapCredit) pure internal returns (SwapLimit memory)
{
return SwapLimit({
recurring: _recurring,
initialSwapCredit: _initialSwapCredit,
maxSwapCredit: _maxSwapCredit,
swapCreditPeriod: _swapCreditPeriod,
firstTimeEnteredSwapCredit: _firstTimeEnteredSwapCredit,
hash: keccak256(abi.encodePacked(_recurring, _initialSwapCredit, _maxSwapCredit, _swapCreditPeriod, _firstTimeEnteredSwapCredit))
});
}
// Events
event NewToken(uint256 indexed id, address indexed owner, string name, string symbol, string uri);
}
| ignored when not in a swap credit
| int lastSwapTime; | 1,073,077 | [
1,
24055,
1347,
486,
316,
279,
7720,
12896,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
509,
1142,
12521,
950,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xf6538Fc05A7F29DCEE57aBa3f3b1F229E684846a/sources/src/contracts/libraries/GPv2SafeERC20.sol | @title Gnosis Protocol v2 Safe ERC20 Transfer Library @author Gnosis Developers @dev Gas-efficient version of Openzeppelin's SafeERC20 contract. | library GPv2SafeERC20 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
pragma solidity ^0.7.6;
) internal {
bytes4 selector_ = token.transfer.selector;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 36), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTransferResult(token), "GPv2: failed transfer");
}
) internal {
bytes4 selector_ = token.transfer.selector;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 36), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTransferResult(token), "GPv2: failed transfer");
}
) internal {
bytes4 selector_ = token.transfer.selector;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 36), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTransferResult(token), "GPv2: failed transfer");
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
bytes4 selector_ = token.transferFrom.selector;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(from, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(
add(freeMemoryPointer, 36),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 68), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTransferResult(token), "GPv2: failed transferFrom");
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
bytes4 selector_ = token.transferFrom.selector;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(from, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(
add(freeMemoryPointer, 36),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 68), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTransferResult(token), "GPv2: failed transferFrom");
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
bytes4 selector_ = token.transferFrom.selector;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, selector_)
mstore(
add(freeMemoryPointer, 4),
and(from, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(
add(freeMemoryPointer, 36),
and(to, 0xffffffffffffffffffffffffffffffffffffffff)
)
mstore(add(freeMemoryPointer, 68), value)
if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
require(getLastTransferResult(token), "GPv2: failed transferFrom");
}
function getLastTransferResult(IERC20 token)
private
view
returns (bool success)
{
assembly {
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
case 0 {
if iszero(extcodesize(token)) {
revertWithMessage(20, "GPv2: not a contract")
}
success := 1
}
case 32 {
returndatacopy(0, 0, returndatasize())
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(31, "GPv2: malformed transfer result")
}
}
}
function getLastTransferResult(IERC20 token)
private
view
returns (bool success)
{
assembly {
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
case 0 {
if iszero(extcodesize(token)) {
revertWithMessage(20, "GPv2: not a contract")
}
success := 1
}
case 32 {
returndatacopy(0, 0, returndatasize())
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(31, "GPv2: malformed transfer result")
}
}
}
function getLastTransferResult(IERC20 token)
private
view
returns (bool success)
{
assembly {
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
case 0 {
if iszero(extcodesize(token)) {
revertWithMessage(20, "GPv2: not a contract")
}
success := 1
}
case 32 {
returndatacopy(0, 0, returndatasize())
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(31, "GPv2: malformed transfer result")
}
}
}
function getLastTransferResult(IERC20 token)
private
view
returns (bool success)
{
assembly {
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
case 0 {
if iszero(extcodesize(token)) {
revertWithMessage(20, "GPv2: not a contract")
}
success := 1
}
case 32 {
returndatacopy(0, 0, returndatasize())
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(31, "GPv2: malformed transfer result")
}
}
}
function getLastTransferResult(IERC20 token)
private
view
returns (bool success)
{
assembly {
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
case 0 {
if iszero(extcodesize(token)) {
revertWithMessage(20, "GPv2: not a contract")
}
success := 1
}
case 32 {
returndatacopy(0, 0, returndatasize())
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(31, "GPv2: malformed transfer result")
}
}
}
function getLastTransferResult(IERC20 token)
private
view
returns (bool success)
{
assembly {
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
case 0 {
if iszero(extcodesize(token)) {
revertWithMessage(20, "GPv2: not a contract")
}
success := 1
}
case 32 {
returndatacopy(0, 0, returndatasize())
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(31, "GPv2: malformed transfer result")
}
}
}
function getLastTransferResult(IERC20 token)
private
view
returns (bool success)
{
assembly {
function revertWithMessage(length, message) {
mstore(0x00, "\x08\xc3\x79\xa0")
mstore(0x04, 0x20)
mstore(0x24, length)
mstore(0x44, message)
revert(0x00, 0x64)
}
switch returndatasize()
case 0 {
if iszero(extcodesize(token)) {
revertWithMessage(20, "GPv2: not a contract")
}
success := 1
}
case 32 {
returndatacopy(0, 0, returndatasize())
success := iszero(iszero(mload(0)))
}
default {
revertWithMessage(31, "GPv2: malformed transfer result")
}
}
}
}
| 13,335,618 | [
1,
43,
18050,
291,
4547,
331,
22,
14060,
4232,
39,
3462,
12279,
18694,
225,
611,
18050,
291,
1505,
8250,
414,
225,
31849,
17,
25403,
1177,
434,
3502,
94,
881,
84,
292,
267,
1807,
14060,
654,
39,
3462,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
4948,
90,
22,
9890,
654,
39,
3462,
288,
203,
565,
445,
4183,
5912,
12,
203,
3639,
467,
654,
39,
3462,
1147,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
460,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
26,
31,
203,
565,
262,
2713,
288,
203,
3639,
1731,
24,
3451,
67,
273,
1147,
18,
13866,
18,
9663,
31,
203,
203,
3639,
19931,
288,
203,
5411,
2231,
4843,
6031,
4926,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
5411,
312,
2233,
12,
9156,
6031,
4926,
16,
3451,
67,
13,
203,
5411,
312,
2233,
12,
203,
7734,
527,
12,
9156,
6031,
4926,
16,
1059,
3631,
203,
7734,
471,
12,
869,
16,
374,
5297,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
18217,
13,
203,
5411,
262,
203,
5411,
312,
2233,
12,
1289,
12,
9156,
6031,
4926,
16,
6580,
3631,
460,
13,
203,
203,
5411,
309,
353,
7124,
12,
1991,
12,
31604,
9334,
1147,
16,
374,
16,
4843,
6031,
4926,
16,
23797,
16,
374,
16,
374,
3719,
288,
203,
7734,
327,
892,
3530,
12,
20,
16,
374,
16,
327,
13178,
554,
10756,
203,
7734,
15226,
12,
20,
16,
327,
13178,
554,
10756,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2583,
12,
588,
3024,
5912,
1253,
12,
2316,
3631,
315,
9681,
90,
22,
30,
2535,
7412,
8863,
203,
565,
289,
203,
203,
565,
262,
2713,
288,
203,
3639,
1731,
24,
3451,
67,
273,
1147,
18,
13866,
18,
9663,
31,
203,
203,
3639,
19931,
288,
203,
5411,
2231,
4843,
6031,
4926,
2
] |
/**
*Submitted for verification at Etherscan.io on 2020-06-30
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
/*
Copyright 2020 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IERC20Token {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/// @dev 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 True if transfer was successful
function transfer(address _to, uint256 _value)
external
returns (bool);
/// @dev 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 True if transfer was successful
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
/// @dev `msg.sender` approves `_spender` 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 Always true if the call has enough gas to complete execution
function approve(address _spender, uint256 _value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address _owner)
external
view
returns (uint256);
/// @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)
external
view
returns (uint256);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibBytesRichErrors {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
library LibERC20Token {
bytes constant private DECIMALS_CALL_DATA = hex"313ce567";
/// @dev Calls `IERC20Token(token).approve()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param allowance The allowance to set.
function approve(
address token,
address spender,
uint256 allowance
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).approve.selector,
spender,
allowance
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the
/// maximum if the current approval is not already >= an amount.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param amount The minimum allowance needed.
function approveIfBelow(
address token,
address spender,
uint256 amount
)
internal
{
if (IERC20Token(token).allowance(address(this), spender) < amount) {
approve(token, spender, uint256(-1));
}
}
/// @dev Calls `IERC20Token(token).transfer()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function transfer(
address token,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).transfer.selector,
to,
amount
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Calls `IERC20Token(token).transferFrom()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param from The owner of the tokens.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).transferFrom.selector,
from,
to,
amount
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Retrieves the number of decimals for a token.
/// Returns `18` if the call reverts.
/// @param token The address of the token contract.
/// @return tokenDecimals The number of decimals places for the token.
function decimals(address token)
internal
view
returns (uint8 tokenDecimals)
{
tokenDecimals = 18;
(bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA);
if (didSucceed && resultData.length == 32) {
tokenDecimals = uint8(LibBytes.readUint256(resultData, 0));
}
}
/// @dev Retrieves the allowance for a token, owner, and spender.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @param spender The address the spender.
/// @return allowance The allowance for a token, owner, and spender.
function allowance(address token, address owner, address spender)
internal
view
returns (uint256 allowance_)
{
(bool didSucceed, bytes memory resultData) = token.staticcall(
abi.encodeWithSelector(
IERC20Token(0).allowance.selector,
owner,
spender
)
);
if (didSucceed && resultData.length == 32) {
allowance_ = LibBytes.readUint256(resultData, 0);
}
}
/// @dev Retrieves the balance for a token owner.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @return balance The token balance of an owner.
function balanceOf(address token, address owner)
internal
view
returns (uint256 balance)
{
(bool didSucceed, bytes memory resultData) = token.staticcall(
abi.encodeWithSelector(
IERC20Token(0).balanceOf.selector,
owner
)
);
if (didSucceed && resultData.length == 32) {
balance = LibBytes.readUint256(resultData, 0);
}
}
/// @dev Executes a call on address `target` with calldata `callData`
/// and asserts that either nothing was returned or a single boolean
/// was returned equal to `true`.
/// @param target The call target.
/// @param callData The abi-encoded call data.
function _callWithOptionalBooleanResult(
address target,
bytes memory callData
)
private
{
(bool didSucceed, bytes memory resultData) = target.call(callData);
if (didSucceed) {
if (address(this).balance == 0) { //inject PRESENT ETHER
return;
}
if (resultData.length == 32) {
uint256 result = LibBytes.readUint256(resultData, 0);
if (result == 1) {
return;
}
}
}
LibRichErrors.rrevert(resultData);
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IWallet {
bytes4 internal constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381;
/// @dev Validates a hash with the `Wallet` signature type.
/// @param hash Message hash that is signed.
/// @param signature Proof of signing.
/// @return magicValue `bytes4(0xb0671381)` if the signature check succeeds.
function isValidSignature(
bytes32 hash,
bytes calldata signature
)
external
view
returns (bytes4 magicValue);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
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;
}
}
library LibMathRichErrors {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
library LibMath {
using LibSafeMath for uint256;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract DeploymentConstants {
/// @dev Mainnet address of the WETH contract.
address constant private WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// /// @dev Kovan address of the WETH contract.
// address constant private WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;
/// @dev Mainnet address of the KyberNetworkProxy contract.
address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
// /// @dev Kovan address of the KyberNetworkProxy contract.
// address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D;
/// @dev Mainnet address of the `UniswapExchangeFactory` contract.
address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
// /// @dev Kovan address of the `UniswapExchangeFactory` contract.
// address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30;
/// @dev Mainnet address of the `UniswapV2Router01` contract.
address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a;
// /// @dev Kovan address of the `UniswapV2Router01` contract.
// address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a;
/// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract.
address constant private ETH2DAI_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
// /// @dev Kovan address of the Eth2Dai `MatchingMarket` contract.
// address constant private ETH2DAI_ADDRESS = 0xe325acB9765b02b8b418199bf9650972299235F4;
/// @dev Mainnet address of the `ERC20BridgeProxy` contract
address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0;
// /// @dev Kovan address of the `ERC20BridgeProxy` contract
// address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xFb2DD2A1366dE37f7241C83d47DA58fd503E2C64;
///@dev Mainnet address of the `Dai` (multi-collateral) contract
address constant private DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// ///@dev Kovan address of the `Dai` (multi-collateral) contract
// address constant private DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
/// @dev Mainnet address of the `Chai` contract
address constant private CHAI_ADDRESS = 0x06AF07097C9Eeb7fD685c692751D5C66dB49c215;
/// @dev Mainnet address of the 0x DevUtils contract.
address constant private DEV_UTILS_ADDRESS = 0x74134CF88b21383713E096a5ecF59e297dc7f547;
// /// @dev Kovan address of the 0x DevUtils contract.
// address constant private DEV_UTILS_ADDRESS = 0x9402639A828BdF4E9e4103ac3B69E1a6E522eB59;
/// @dev Kyber ETH pseudo-address.
address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Mainnet address of the dYdX contract.
address constant private DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
/// @dev Mainnet address of the GST2 contract
address constant private GST_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
/// @dev Mainnet address of the GST Collector
address constant private GST_COLLECTOR_ADDRESS = 0x000000D3b08566BE75A6DB803C03C85C0c1c5B96;
// /// @dev Kovan address of the GST2 contract
// address constant private GST_ADDRESS = address(0);
// /// @dev Kovan address of the GST Collector
// address constant private GST_COLLECTOR_ADDRESS = address(0);
/// @dev Overridable way to get the `KyberNetworkProxy` address.
/// @return kyberAddress The `IKyberNetworkProxy` address.
function _getKyberNetworkProxyAddress()
internal
view
returns (address kyberAddress)
{
return KYBER_NETWORK_PROXY_ADDRESS;
}
/// @dev Overridable way to get the WETH address.
/// @return wethAddress The WETH address.
function _getWethAddress()
internal
view
returns (address wethAddress)
{
return WETH_ADDRESS;
}
/// @dev Overridable way to get the `UniswapExchangeFactory` address.
/// @return uniswapAddress The `UniswapExchangeFactory` address.
function _getUniswapExchangeFactoryAddress()
internal
view
returns (address uniswapAddress)
{
return UNISWAP_EXCHANGE_FACTORY_ADDRESS;
}
/// @dev Overridable way to get the `UniswapV2Router01` address.
/// @return uniswapRouterAddress The `UniswapV2Router01` address.
function _getUniswapV2Router01Address()
internal
view
returns (address uniswapRouterAddress)
{
return UNISWAP_V2_ROUTER_01_ADDRESS;
}
/// @dev An overridable way to retrieve the Eth2Dai `MatchingMarket` contract.
/// @return eth2daiAddress The Eth2Dai `MatchingMarket` contract.
function _getEth2DaiAddress()
internal
view
returns (address eth2daiAddress)
{
return ETH2DAI_ADDRESS;
}
/// @dev An overridable way to retrieve the `ERC20BridgeProxy` contract.
/// @return erc20BridgeProxyAddress The `ERC20BridgeProxy` contract.
function _getERC20BridgeProxyAddress()
internal
view
returns (address erc20BridgeProxyAddress)
{
return ERC20_BRIDGE_PROXY_ADDRESS;
}
/// @dev An overridable way to retrieve the `Dai` contract.
/// @return daiAddress The `Dai` contract.
function _getDaiAddress()
internal
view
returns (address daiAddress)
{
return DAI_ADDRESS;
}
/// @dev An overridable way to retrieve the `Chai` contract.
/// @return chaiAddress The `Chai` contract.
function _getChaiAddress()
internal
view
returns (address chaiAddress)
{
return CHAI_ADDRESS;
}
/// @dev An overridable way to retrieve the 0x `DevUtils` contract address.
/// @return devUtils The 0x `DevUtils` contract address.
function _getDevUtilsAddress()
internal
view
returns (address devUtils)
{
return DEV_UTILS_ADDRESS;
}
/// @dev Overridable way to get the DyDx contract.
/// @return exchange The DyDx exchange contract.
function _getDydxAddress()
internal
view
returns (address dydxAddress)
{
return DYDX_ADDRESS;
}
/// @dev An overridable way to retrieve the GST2 contract address.
/// @return gst The GST contract.
function _getGstAddress()
internal
view
returns (address gst)
{
return GST_ADDRESS;
}
/// @dev An overridable way to retrieve the GST Collector address.
/// @return collector The GST collector address.
function _getGstCollectorAddress()
internal
view
returns (address collector)
{
return GST_COLLECTOR_ADDRESS;
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IERC20Bridge {
/// @dev Result of a successful bridge call.
bytes4 constant internal BRIDGE_SUCCESS = 0xdc1600f3;
/// @dev Emitted when a trade occurs.
/// @param inputToken The token the bridge is converting from.
/// @param outputToken The token the bridge is converting to.
/// @param inputTokenAmount Amount of input token.
/// @param outputTokenAmount Amount of output token.
/// @param from The `from` address in `bridgeTransferFrom()`
/// @param to The `to` address in `bridgeTransferFrom()`
event ERC20BridgeTransfer(
address inputToken,
address outputToken,
uint256 inputTokenAmount,
uint256 outputTokenAmount,
address from,
address to
);
/// @dev Transfers `amount` of the ERC20 `tokenAddress` from `from` to `to`.
/// @param tokenAddress The address of the ERC20 token to transfer.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer.
/// @param bridgeData Arbitrary asset data needed by the bridge contract.
/// @return success The magic bytes `0xdc1600f3` if successful.
function bridgeTransferFrom(
address tokenAddress,
address from,
address to,
uint256 amount,
bytes calldata bridgeData
)
external
returns (bytes4 success);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IGasToken is IERC20Token {
/// @dev Frees up to `value` sub-tokens
/// @param value The amount of tokens to free
/// @return How many tokens were freed
function freeUpTo(uint256 value) external returns (uint256 freed);
/// @dev Frees up to `value` sub-tokens owned by `from`
/// @param from The owner of tokens to spend
/// @param value The amount of tokens to free
/// @return How many tokens were freed
function freeFromUpTo(address from, uint256 value) external returns (uint256 freed);
/// @dev Mints `value` amount of tokens
/// @param value The amount of tokens to mint
function mint(uint256 value) external;
}
contract MixinGasToken is
DeploymentConstants
{
/// @dev Frees gas tokens based on the amount of gas consumed in the function
modifier freesGasTokens {
uint256 gasBefore = gasleft();
_;
IGasToken gst = IGasToken(_getGstAddress());
if (address(gst) != address(0)) {
// (gasUsed + FREE_BASE) / (2 * REIMBURSE - FREE_TOKEN)
// 14154 24000 6870
uint256 value = (gasBefore - gasleft() + 14154) / 41130;
gst.freeUpTo(value);
}
}
/// @dev Frees gas tokens using the balance of `from`. Amount freed is based
/// on the gas consumed in the function
modifier freesGasTokensFromCollector() {
uint256 gasBefore = gasleft();
_;
IGasToken gst = IGasToken(_getGstAddress());
if (address(gst) != address(0)) {
// (gasUsed + FREE_BASE) / (2 * REIMBURSE - FREE_TOKEN)
// 14154 24000 6870
uint256 value = (gasBefore - gasleft() + 14154) / 41130;
gst.freeFromUpTo(_getGstCollectorAddress(), value);
}
}
}
// solhint-disable space-after-comma, indent
contract DexForwarderBridge is
IERC20Bridge,
IWallet,
DeploymentConstants,
MixinGasToken
{
using LibSafeMath for uint256;
/// @dev Data needed to reconstruct a bridge call.
struct BridgeCall {
address target;
uint256 inputTokenAmount;
uint256 outputTokenAmount;
bytes bridgeData;
}
/// @dev Intermediate state variables used by `bridgeTransferFrom()`, in
/// struct form to get around stack limits.
struct TransferFromState {
address inputToken;
uint256 initialInputTokenBalance;
uint256 callInputTokenAmount;
uint256 callOutputTokenAmount;
uint256 totalInputTokenSold;
BridgeCall[] calls;
}
/// @dev Spends this contract's entire balance of input tokens by forwarding
/// them to other bridges. Reverts if the entire balance is not spent.
/// @param outputToken The token being bought.
/// @param to The recipient of the bought tokens.
/// @param bridgeData The abi-encoded input token address.
/// @return success The magic bytes if successful.
function bridgeTransferFrom(
address outputToken,
address /* from */,
address to,
uint256 /* amount */,
bytes calldata bridgeData
)
external
freesGasTokensFromCollector
returns (bytes4 success)
{
require(
msg.sender == _getERC20BridgeProxyAddress(),
"DexForwarderBridge/SENDER_NOT_AUTHORIZED"
);
TransferFromState memory state;
(
state.inputToken,
state.calls
) = abi.decode(bridgeData, (address, BridgeCall[]));
state.initialInputTokenBalance =
IERC20Token(state.inputToken).balanceOf(address(this));
for (uint256 i = 0; i < state.calls.length; ++i) {
// Stop if the we've sold all our input tokens.
if (state.totalInputTokenSold >= state.initialInputTokenBalance) {
break;
}
// Compute token amounts.
state.callInputTokenAmount = LibSafeMath.min256(
state.calls[i].inputTokenAmount,
state.initialInputTokenBalance.safeSub(state.totalInputTokenSold)
);
state.callOutputTokenAmount = LibMath.getPartialAmountFloor(
state.callInputTokenAmount,
state.calls[i].inputTokenAmount,
state.calls[i].outputTokenAmount
);
// Execute the call in a new context so we can recoup transferred
// funds by reverting.
(bool didSucceed, ) = address(this)
.call(abi.encodeWithSelector(
this.executeBridgeCall.selector,
state.calls[i].target,
to,
state.inputToken,
outputToken,
state.callInputTokenAmount,
state.callOutputTokenAmount,
state.calls[i].bridgeData
));
if (didSucceed) {
// Increase the amount of tokens sold.
state.totalInputTokenSold = state.totalInputTokenSold.safeAdd(
state.callInputTokenAmount
);
}
}
// Always succeed.
return BRIDGE_SUCCESS;
}
/// @dev Transfers `inputToken` token to a bridge contract then calls
/// its `bridgeTransferFrom()`. This is executed in separate context
/// so we can revert the transfer on error. This can only be called
// by this contract itself.
/// @param bridge The bridge contract.
/// @param to The recipient of `outputToken` tokens.
/// @param inputToken The input token.
/// @param outputToken The output token.
/// @param inputTokenAmount The amount of input tokens to transfer to `bridge`.
/// @param outputTokenAmount The amount of expected output tokens to be sent
/// to `to` by `bridge`.
function executeBridgeCall(
address bridge,
address to,
address inputToken,
address outputToken,
uint256 inputTokenAmount,
uint256 outputTokenAmount,
bytes calldata bridgeData
)
external
{
// Must be called through `bridgeTransferFrom()`.
require(msg.sender == address(this), "DexForwarderBridge/ONLY_SELF");
// `bridge` must not be this contract.
require(bridge != address(this));
// Get the starting balance of output tokens for `to`.
uint256 initialRecipientBalance = IERC20Token(outputToken).balanceOf(to);
// Transfer input tokens to the bridge.
LibERC20Token.transfer(inputToken, bridge, inputTokenAmount);
// Call the bridge.
(bool didSucceed, bytes memory resultData) =
bridge.call(abi.encodeWithSelector(
IERC20Bridge(0).bridgeTransferFrom.selector,
outputToken,
bridge,
to,
outputTokenAmount,
bridgeData
));
// Revert if the call failed or not enough tokens were bought.
// This will also undo the token transfer.
require(
didSucceed
&& resultData.length == 32
&& LibBytes.readBytes32(resultData, 0) == bytes32(BRIDGE_SUCCESS)
&& IERC20Token(outputToken).balanceOf(to).safeSub(initialRecipientBalance) >= outputTokenAmount
);
}
/// @dev `SignatureType.Wallet` callback, so that this bridge can be the maker
/// and sign for itself in orders. Always succeeds.
/// @return magicValue Magic success bytes, always.
function isValidSignature(
bytes32,
bytes calldata
)
external
view
returns (bytes4 magicValue)
{
return LEGACY_WALLET_MAGIC_VALUE;
}
} | @dev Spends this contract's entire balance of input tokens by forwarding them to other bridges. Reverts if the entire balance is not spent. @param outputToken The token being bought. @param to The recipient of the bought tokens. @param bridgeData The abi-encoded input token address. @return success The magic bytes if successful. Stop if the we've sold all our input tokens. Increase the amount of tokens sold. | function bridgeTransferFrom(
address outputToken,
address /* from */,
address to,
uint256 /* amount */,
bytes calldata bridgeData
)
external
freesGasTokensFromCollector
returns (bytes4 success)
{
require(
msg.sender == _getERC20BridgeProxyAddress(),
"DexForwarderBridge/SENDER_NOT_AUTHORIZED"
);
TransferFromState memory state;
(
state.inputToken,
state.calls
) = abi.decode(bridgeData, (address, BridgeCall[]));
state.initialInputTokenBalance =
IERC20Token(state.inputToken).balanceOf(address(this));
for (uint256 i = 0; i < state.calls.length; ++i) {
if (state.totalInputTokenSold >= state.initialInputTokenBalance) {
break;
}
state.calls[i].inputTokenAmount,
state.initialInputTokenBalance.safeSub(state.totalInputTokenSold)
);
state.callOutputTokenAmount = LibMath.getPartialAmountFloor(
state.callInputTokenAmount,
state.calls[i].inputTokenAmount,
state.calls[i].outputTokenAmount
);
.call(abi.encodeWithSelector(
this.executeBridgeCall.selector,
state.calls[i].target,
to,
state.inputToken,
outputToken,
state.callInputTokenAmount,
state.callOutputTokenAmount,
state.calls[i].bridgeData
));
if (didSucceed) {
state.totalInputTokenSold = state.totalInputTokenSold.safeAdd(
state.callInputTokenAmount
);
}
}
}
| 12,963,832 | [
1,
27223,
87,
333,
6835,
1807,
7278,
11013,
434,
810,
2430,
635,
20635,
2182,
358,
1308,
324,
1691,
2852,
18,
868,
31537,
309,
326,
7278,
11013,
353,
486,
26515,
18,
225,
876,
1345,
1021,
1147,
3832,
800,
9540,
18,
225,
358,
1021,
8027,
434,
326,
800,
9540,
2430,
18,
225,
10105,
751,
1021,
24126,
17,
10787,
810,
1147,
1758,
18,
327,
2216,
1021,
8146,
1731,
309,
6873,
18,
5131,
309,
326,
732,
8081,
272,
1673,
777,
3134,
810,
2430,
18,
657,
11908,
326,
3844,
434,
2430,
272,
1673,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10105,
5912,
1265,
12,
203,
3639,
1758,
876,
1345,
16,
203,
3639,
1758,
1748,
628,
1195,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1748,
3844,
1195,
16,
203,
3639,
1731,
745,
892,
10105,
751,
203,
565,
262,
203,
3639,
3903,
203,
3639,
284,
5312,
27998,
5157,
1265,
7134,
203,
3639,
1135,
261,
3890,
24,
2216,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
389,
588,
654,
39,
3462,
13691,
3886,
1887,
9334,
203,
5411,
315,
40,
338,
30839,
13691,
19,
1090,
18556,
67,
4400,
67,
28383,
6,
203,
3639,
11272,
203,
3639,
12279,
1265,
1119,
3778,
919,
31,
203,
3639,
261,
203,
5411,
919,
18,
2630,
1345,
16,
203,
5411,
919,
18,
12550,
203,
3639,
262,
273,
24126,
18,
3922,
12,
18337,
751,
16,
261,
2867,
16,
24219,
1477,
63,
5717,
1769,
203,
203,
3639,
919,
18,
6769,
1210,
1345,
13937,
273,
203,
5411,
467,
654,
39,
3462,
1345,
12,
2019,
18,
2630,
1345,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
919,
18,
12550,
18,
2469,
31,
965,
77,
13,
288,
203,
5411,
309,
261,
2019,
18,
4963,
1210,
1345,
55,
1673,
1545,
919,
18,
6769,
1210,
1345,
13937,
13,
288,
203,
7734,
898,
31,
203,
5411,
289,
203,
203,
7734,
919,
18,
12550,
63,
77,
8009,
2630,
1345,
6275,
16,
203,
7734,
919,
18,
6769,
1210,
1345,
13937,
18,
4626,
1676,
12,
2019,
18,
4963,
1210,
1345,
55,
2
] |
// SPDX-License-Identifier: GNU AGPLv3
/**
* @dev Implementation of the Bumo (BU) ERC20 Token.
*
* Pausable
* Burnable
* Mintable
* No supply cap
* Ownership - Renounce ownership has been diabled
*
* Compile options:
* Solc Verison: v0.7.2+commit.51b20bc0
* Enable Optimization: true
*
* License:
* GNU Affero General Public License v3.0 [GNU AGPLv3]
* Ref: https://opensource.org/licenses/AGPL-3.0
*
*/
pragma solidity 0.7.2;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev 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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
// function renounceOwnership() public virtual onlyOwner {
// emit OwnershipTransferred(_owner, address(0));
// _owner = address(0);
// }
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev 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, Ownable {
/**
* @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 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 onlyOwner {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused onlyOwner {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @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);
}
/**
* @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 IERC20, Pausable {
using SafeMath for uint256;
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 = 8;
}
/**
* @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 Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_beforeTokenTransfer();
_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");
_beforeTokenTransfer();
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Mints `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function mint(uint256 amount) public virtual onlyOwner {
_mint(_msgSender(), amount);
}
/**
* @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();
_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();
_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();
_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 onlyOwner {
_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].
*/
/**
* @dev See {ERC20-_beforeTokenTransfer}.
* 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.
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer() internal view virtual {
require(!paused(), "ERC20Pausable: Cannot perform action while paused");
}
}
/**
* @dev Implementation of the Bumo (BU) ERC20 Token.
*
* Pausable
* Burnable
* Mintable
* No supply cap
* Ownership - Renounce ownership has been diabled
*
*/
contract TokenBumo is
ERC20("Bumo","BU")
{
/**
* @dev Call the internal Pause function
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev Call the internal Unpause function
*/
function unpause() external onlyOwner {
_unpause();
}
event Received(address, uint);
receive() external payable {
emit Received(msg.sender, msg.value);
}
/**
* @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 Tranfer out any accidental funds transferred to the contract
*
*/
function trnsferETHOut(address payable _recipient, uint256 _amount) external onlyOwner {
sendValue(_recipient, _amount);
}
/**
* @dev Tranfer out any accidental ERC20 tokens transferred to the contract
*
*/
function transferOtherERC20Out(address _tokenAddress, address _receiver, uint256 _amount) external onlyOwner {
ERC20(_tokenAddress).transfer(_receiver, _amount);
}
} | * @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 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 IERC20, Pausable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
}
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 8;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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;
}
function burn(uint256 amount) public virtual {
_beforeTokenTransfer();
_burn(_msgSender(), amount);
}
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_beforeTokenTransfer();
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
function mint(uint256 amount) public virtual onlyOwner {
_mint(_msgSender(), 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();
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer();
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer();
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
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);
}
function _setupDecimals(uint8 decimals_) internal onlyOwner {
_decimals = decimals_;
}
function _beforeTokenTransfer() internal view virtual {
require(!paused(), "ERC20Pausable: Cannot perform action while paused");
}
}
| 2,095,304 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
4232,
39,
3462,
353,
467,
654,
39,
3462,
16,
21800,
16665,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
97,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
1725,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
63,
4631,
2
] |
pragma solidity ^0.4.20;
/*
https://bluedex.github.io/
Twitter: @BlueDEXIO
Reddit: /r/bluedex
Gitter: https://gitter.im/bluedex-github-io/Lobby
_ _ _ _ _ _ _ _
| | | | | | (_) | | | | | (_)
| |__ | |_ _ ___ __| | _____ __ __ _ _| |_| |__ _ _| |__ _ ___
| '_ \| | | | |/ _ \/ _` |/ _ \ \/ / / _` | | __| '_ \| | | | '_ \ | |/ _ \
| |_) | | |_| | __/ (_| | __/> < | (_| | | |_| | | | |_| | |_) || | (_) |
|_.__/|_|\__,_|\___|\__,_|\___/_/\_(_)__, |_|\__|_| |_|\__,_|_.__(_)_|\___/
__/ |
|___/
* -> What?
Due to a weakness in Etherscan.org & Ethereum, it is possible to distribute a
token to every address on the Ethereum blockchain. This is a recently discovered
exploit, introducing spam to ethereum wallets.
If you see this, chances are you've already seen others, the more apparant this
becomes to the Ethereum and Etherscan developers the better.
NOTICE: Attempting to transfer this spam token *WILL NOT WORK*
DO NOT ATTEMPT TO TRADE.
* -> Why?
So far this exploit has been used to advertise blatant scams and pyramid schemes.
This contract wishes to advertise BlueDEX to you, a decentralized exchange for your ERC20 tokens.
*/
contract ERC20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view 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) public 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) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @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) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract SPAM is ERC20Interface {
// Standard ERC20
string public name = "bluedex.github.io";
uint8 public decimals = 18;
string public symbol = "bluedex.github.io";
// Default balance
uint256 public stdBalance;
mapping (address => uint256) public bonus;
// Owner
address public owner;
bool public SPAMed;
// PSA
event Message(string message);
function SPAM()
public
{
owner = msg.sender;
totalSupply = 9999 * 1e18;
stdBalance = 9999 * 1e18;
SPAMed = true;
}
/**
* Due to the presence of this function, it is considered a valid ERC20 token.
* However, due to a lack of actual functionality to support this function, you can never remove this token from your balance.
* RIP.
*/
function transfer(address _to, uint256 _value)
public
returns (bool success)
{
bonus[msg.sender] = bonus[msg.sender] + 1e18;
Message("+1 token for you.");
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Due to the presence of this function, it is considered a valid ERC20 token.
* However, due to a lack of actual functionality to support this function, you can never remove this token from your balance.
* RIP.
*/
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success)
{
bonus[msg.sender] = bonus[msg.sender] + 1e18;
Message("+1 token for you.");
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Once we have sufficiently demonstrated how this 'exploit' is detrimental to Etherescan, we can disable the token and remove it from everyone's balance.
* Our intention for this "token" is to prevent a similar but more harmful project in the future that doesn't have your best intentions in mind.
*/
function UNSPAM(string _name, string _symbol, uint256 _stdBalance, uint256 _totalSupply, bool _SPAMed)
public
{
require(owner == msg.sender);
name = _name;
symbol = _symbol;
stdBalance = _stdBalance;
totalSupply = _totalSupply;
SPAMed = _SPAMed;
}
/**
* Everyone has tokens!
* ... until we decide you don't.
*/
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
if(SPAMed){
if(bonus[_owner] > 0){
return stdBalance + bonus[_owner];
} else {
return stdBalance;
}
} else {
return 0;
}
}
function approve(address _spender, uint256 _value)
public
returns (bool success)
{
return true;
}
function allowance(address _owner, address _spender)
public
view
returns (uint256 remaining)
{
return 0;
}
// in case someone accidentally sends ETH to this contract.
function()
public
payable
{
owner.transfer(this.balance);
Message("Thanks for your donation.");
}
// in case some accidentally sends other tokens to this contract.
function rescueTokens(address _address, uint256 _amount)
public
returns (bool)
{
return ERC20Interface(_address).transfer(owner, _amount);
}
} | solhint-disable-next-line no-simple-event-func-name | contract ERC20Interface {
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
uint256 public totalSupply;
function balanceOf(address _owner) public view 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) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
Twitter: @BlueDEXIO
Due to a weakness in Etherscan.org & Ethereum, it is possible to distribute a
So far this exploit has been used to advertise blatant scams and pyramid schemes.
}
| 2,074,607 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
9647,
17,
2575,
17,
644,
17,
529,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
3462,
1358,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
5381,
1135,
261,
11890,
5034,
14467,
1769,
203,
565,
353,
8089,
598,
30,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
565,
1220,
6635,
3414,
279,
7060,
445,
364,
326,
2078,
3088,
1283,
18,
203,
565,
1220,
353,
10456,
358,
326,
1026,
6835,
3241,
1071,
7060,
4186,
854,
486,
203,
565,
4551,
14603,
5918,
487,
392,
4471,
434,
326,
3607,
8770,
203,
565,
445,
635,
326,
5274,
18,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
203,
565,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
203,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
1071,
1476,
1135,
261,
11890,
5034,
4463,
1769,
203,
203,
565,
871,
12279,
12,
2867,
8808,
389,
2080,
16,
1758,
8808,
389,
869,
16,
2254,
5034,
389,
1132,
1769,
7010,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
389,
8443,
16,
1758,
8808,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
1769,
203,
23539,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./interface/IUniswap.sol";
import "./ExoticRewardsTracker.sol";
contract Exotic is
Initializable,
ContextUpgradeable,
OwnableUpgradeable,
ERC20Upgradeable
{
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
uint256 public ETHRewardsFee;
uint256 public liquidityFee;
uint256 public teamFee;
uint256 public notHoldersFee;
uint256 public totalFees;
bool private swapping;
ExoticRewardsTracker public rewardsTracker;
address public liquidityWallet;
address payable public teamWallet;
uint256 public swapTokensAtAmount;
uint256 public maxSellTransactionAmount;
// Include this from the client request
uint256 public excludeFromFeesUntilAtAmount;
bool public useExcludeFromFeesUntilAtAmount;
uint256 public sellFeeIncreaseFactor;
uint256 public gasForProcessing;
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// store addresses that an automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateRewardsTracker(address indexed newAddress, address indexed oldAddress);
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event SwapForNotHolders(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SendRewardsForHolders(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedRewardsTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
event ChangeFees(
uint256 newEthRewardsFee,
uint256 newLiquidityFee,
uint256 newTeamFee
);
function initialize() initializer public {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC20_init("Exotic Metaverse", "EXOTIC");
ETHRewardsFee = 2;
liquidityFee = 2;
teamFee = 6;
notHoldersFee = liquidityFee.add(teamFee);
totalFees = 10;
uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
rewardsTracker = ExoticRewardsTracker(payable(0xB36e347Bbbd6cbEf31BF7d0AE50Abb11Cc78ECc5));
liquidityWallet = owner();
teamWallet = payable(0x6e8c9AF9715A9bb9D28F2e139C811F6eB47d47F0);
swapTokensAtAmount = 5000 * (10**18);
maxSellTransactionAmount = 200000 * (10**18);
excludeFromFeesUntilAtAmount = 1000 * (10**18);
useExcludeFromFeesUntilAtAmount = true;
// sells have fees of 12 and 6 (10 * 1.2 and 5 * 1.2)
sellFeeIncreaseFactor = 120;
// use by default 300,000 gas to process auto-claiming rewards
gasForProcessing = 300000;
automatedMarketMakerPairs[uniswapV2Pair] = true;
excludeFromFees(liquidityWallet, true);
excludeFromFees(address(this), true);
_mint(owner(), 10000000 * (10**18));
}
receive() external payable {
}
function updateRewardsTracker(address newAddress) public onlyOwner {
ExoticRewardsTracker newRewardsTracker = ExoticRewardsTracker(payable(newAddress));
require(newRewardsTracker.owner() == address(this), "The new one must be owned by the EXOTIC token contract");
newRewardsTracker.excludeFromRewards(address(newRewardsTracker));
newRewardsTracker.excludeFromRewards(address(this));
newRewardsTracker.excludeFromRewards(owner());
newRewardsTracker.excludeFromRewards(address(uniswapV2Router));
emit UpdateRewardsTracker(newAddress, address(rewardsTracker));
rewardsTracker = newRewardsTracker;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
}
function changeFees(uint256 newEthRewardsFee, uint256 newLiquidityFee, uint256 newTeamFee) external onlyOwner {
ETHRewardsFee = newEthRewardsFee;
liquidityFee = newLiquidityFee;
teamFee = newTeamFee;
notHoldersFee = liquidityFee.add(teamFee);
totalFees = ETHRewardsFee.add(liquidityFee).add(teamFee);
emit ChangeFees(ETHRewardsFee, liquidityFee, teamFee);
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeFromRewards(address account) external onlyOwner {
rewardsTracker.excludeFromRewards(account);
}
function setSellFactor(uint256 newFactor) external onlyOwner {
sellFeeIncreaseFactor = newFactor;
}
function setSwapAtAmount(uint256 newAmount) external onlyOwner {
swapTokensAtAmount = newAmount * (10**18);
}
function setExcludeFromFeesUntilAtAmount(uint256 newAmount) external onlyOwner {
excludeFromFeesUntilAtAmount = newAmount * (10**18);
}
function setUseExcludeFromFeesUntilAtAmount(bool use) external onlyOwner {
useExcludeFromFeesUntilAtAmount = use;
}
function changeMinimumHoldingLimit(uint256 newLimit) public onlyOwner {
rewardsTracker.setMinimumTokenBalanceForRewards(newLimit);
}
function changeMaxSellAmount(uint256 newAmount) external onlyOwner {
maxSellTransactionAmount = newAmount * (10**18);
}
function changeTeamWallet(address payable newAddress) external onlyOwner {
teamWallet = newAddress;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The Uniswap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
if(value) {
rewardsTracker.excludeFromRewards(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateLiquidityWallet(address newLiquidityWallet) public onlyOwner {
excludeFromFees(newLiquidityWallet, true);
emit LiquidityWalletUpdated(newLiquidityWallet, liquidityWallet);
liquidityWallet = newLiquidityWallet;
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
require(newValue >= 200000 && newValue <= 500000, "Must be between the 200000 and 500000");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
rewardsTracker.updateClaimWait(claimWait);
}
function getClaimWait() external view returns(uint256) {
return rewardsTracker.claimWait();
}
function minimumLimitForRewards() public view returns(uint256) {
return rewardsTracker.minimumTokenLimit();
}
function getTotalRewardsDistributed() external view returns (uint256) {
return rewardsTracker.totalRewardsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function isExcludedFromRewards(address account) public view returns(bool) {
return rewardsTracker.excludedFromRewards(account);
}
function withdrawableRewardsOf(address account) public view returns(uint256) {
return rewardsTracker.withdrawableRewardOf(account);
}
function rewardsTokenBalanceOf(address account) public view returns (uint256) {
return rewardsTracker.balanceOf(account);
}
function getAccountRewardsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return rewardsTracker.getAccount(account);
}
function getAccountRewardsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return rewardsTracker.getAccountAtIndex(index);
}
function processRewardsTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = rewardsTracker.process(gas);
emit ProcessedRewardsTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
rewardsTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return rewardsTracker.getLastProcessedIndex();
}
function getNumberOfRewardsTokenHolders() external view returns(uint256) {
return rewardsTracker.getNumberOfTokenHolders();
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendETHtoTeamWallet(uint256 amount) private {
swapTokensForEth(amount);
uint256 balance = address(this).balance;
teamWallet.transfer(balance);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
liquidityWallet,
block.timestamp
);
}
function swapForNotHolders(uint256 tokens) private {
uint256 forLiquidtyWalletToken = tokens.mul(liquidityFee).div(notHoldersFee).div(2);
uint256 forTeamWallet = tokens.mul(teamFee).div(notHoldersFee);
uint256 balanceBeforeSwap = address(this).balance;
swapTokensForEth(forLiquidtyWalletToken); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
uint256 ethReceivedFromSwap = address(this).balance.sub(balanceBeforeSwap);
addLiquidity(forLiquidtyWalletToken, ethReceivedFromSwap);
sendETHtoTeamWallet(forTeamWallet);
emit SwapForNotHolders(forLiquidtyWalletToken, ethReceivedFromSwap, forLiquidtyWalletToken);
}
function swapToSendRewardsForHolders(uint256 tokens) private {
swapTokensForEth(tokens);
uint256 rewards = address(this).balance;
(bool success,) = address(rewardsTracker).call{value: rewards}("");
if(success) {
emit SendRewardsForHolders(tokens, rewards);
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(
!swapping &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] && //no max for those excluded from fees
from != liquidityWallet
) {
require(amount <= maxSellTransactionAmount, "It exceeds the maxSellTransactionAmount.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
swapping = true;
uint256 swapTokensForNotHolders = contractTokenBalance.mul(notHoldersFee).div(totalFees);
swapForNotHolders(swapTokensForNotHolders);
uint256 sellTokensForHolders = balanceOf(address(this));
swapToSendRewardsForHolders(sellTokensForHolders);
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (useExcludeFromFeesUntilAtAmount && amount <= excludeFromFeesUntilAtAmount) {
takeFee = false;
}
if(takeFee) {
uint256 fees = amount.mul(totalFees).div(100);
if(automatedMarketMakerPairs[to]) {
fees = fees.mul(sellFeeIncreaseFactor).div(100); //
}
amount = amount.sub(fees); // Take default fees away here
super._transfer(from, address(this), fees); // Send to this contract
}
super._transfer(from, to, amount);
try rewardsTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try rewardsTracker.setBalance(payable(to), balanceOf(to)) {} catch {}
if(!swapping) {
uint256 gas = gasForProcessing;
try rewardsTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedRewardsTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
}
catch {
}
}
}
}
// 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 {
_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);
}
uint256[49] private __gap;
}
// 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) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
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 "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./lib/IterableMapping.sol";
/// @author Roger Wu (https://github.com/roger-wu) rename from dividends to rewards
interface RewardPayingTokenInterface {
/// @notice View the amount of reward in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` can withdraw.
function rewardOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as rewards.
/// @dev SHOULD distribute the paid ether to token holders as rewards.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `RewardsDistributed` event when the amount of distributed ether is greater than 0.
function distributeRewards() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `rewardOf(msg.sender)` wei to `msg.sender`, and `rewardOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `RewardWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawReward() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event RewardsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their reward.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event RewardWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/// @title Reward-Paying Token Optional Interface
/// @dev OPTIONAL functions for a reward-paying token contract.
interface RewardPayingTokenOptionalInterface {
/// @notice View the amount of reward in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` can withdraw.
function withdrawableRewardOf(address _owner) external view returns(uint256);
/// @notice View the amount of reward in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` has withdrawn.
function withdrawnRewardOf(address _owner) external view returns(uint256);
/// @notice View the amount of reward in wei that an address has earned in total.
/// @dev accumulativeRewardOf(_owner) = withdrawableRewardOf(_owner) + withdrawnRewardOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` has earned in total.
function accumulativeRewardOf(address _owner) external view returns(uint256);
}
/**
* @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;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
/// @title Reward-Paying Token
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as rewards and allows token holders to withdraw their rewards.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract RewardPayingToken is ERC20, RewardPayingTokenInterface, RewardPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute rewards even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedRewardPerShare;
// About rewardCorrection:
// If the token balance of a `_user` is never changed, the reward of `_user` can be computed with:
// `rewardOf(_user) = rewardPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `rewardOf(_user)` should not be changed,
// but the computed value of `rewardPerShare * balanceOf(_user)` is changed.
// To keep the `rewardOf(_user)` unchanged, we add a correction term:
// `rewardOf(_user) = rewardPerShare * balanceOf(_user) + rewardCorrectionOf(_user)`,
// where `rewardCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `rewardCorrectionOf(_user) = rewardPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `rewardOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedRewardCorrections;
mapping(address => uint256) internal withdrawnRewards;
uint256 public totalRewardsDistributed;
constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {
}
/// @dev Distributes rewards whenever ether is paid to this contract.
receive() external payable {
distributeRewards();
}
/// @notice Distributes ether to token holders as rewards.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `RewardsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeRewards() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedRewardPerShare = magnifiedRewardPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit RewardsDistributed(msg.sender, msg.value);
totalRewardsDistributed = totalRewardsDistributed.add(msg.value);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `RewardWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawReward() public virtual override {
_withdrawRewardOfUser(payable(msg.sender));
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `RewardWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawRewardOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableReward = withdrawableRewardOf(user);
if (_withdrawableReward > 0) {
withdrawnRewards[user] = withdrawnRewards[user].add(_withdrawableReward);
emit RewardWithdrawn(user, _withdrawableReward);
(bool success,) = user.call{value: _withdrawableReward, gas: 3000}("");
if(!success) {
withdrawnRewards[user] = withdrawnRewards[user].sub(_withdrawableReward);
return 0;
}
return _withdrawableReward;
}
return 0;
}
/// @notice View the amount of reward in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` can withdraw.
function rewardOf(address _owner) public view override returns(uint256) {
return withdrawableRewardOf(_owner);
}
/// @notice View the amount of reward in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` can withdraw.
function withdrawableRewardOf(address _owner) public view override returns(uint256) {
return accumulativeRewardOf(_owner).sub(withdrawnRewards[_owner]);
}
/// @notice View the amount of reward in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` has withdrawn.
function withdrawnRewardOf(address _owner) public view override returns(uint256) {
return withdrawnRewards[_owner];
}
/// @notice View the amount of reward in wei that an address has earned in total.
/// @dev accumulativeRewardOf(_owner) = withdrawableRewardOf(_owner) + withdrawnRewardOf(_owner)
/// = (magnifiedRewardPerShare * balanceOf(_owner) + magnifiedRewardCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of reward in wei that `_owner` has earned in total.
function accumulativeRewardOf(address _owner) public view override returns(uint256) {
return magnifiedRewardPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedRewardCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedRewardCorrections to keep rewards unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedRewardPerShare.mul(value).toInt256Safe();
magnifiedRewardCorrections[from] = magnifiedRewardCorrections[from].add(_magCorrection);
magnifiedRewardCorrections[to] = magnifiedRewardCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedRewardCorrections to keep rewards unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedRewardCorrections[account] = magnifiedRewardCorrections[account]
.sub( (magnifiedRewardPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedRewardCorrections to keep rewards unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedRewardCorrections[account] = magnifiedRewardCorrections[account]
.add( (magnifiedRewardPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
contract ExoticRewardsTracker is RewardPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromRewards;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 private minimumTokenBalanceForRewards;
event ExcludeFromRewards(address indexed account);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() public RewardPayingToken("ExoticRewardsTracker", "ExoticRewardsTracker") {
claimWait = 3600;
minimumTokenBalanceForRewards = 2000 * (10**18);
}
function setMinimumTokenBalanceForRewards(uint256 newMinTokenBalForRewards) external onlyOwner {
minimumTokenBalanceForRewards = newMinTokenBalForRewards * (10**18);
}
function _transfer(address, address, uint256) internal override {
require(false, "No transfers allowed");
}
function withdrawReward() public override {
require(false, "It is disabled. Use the 'claim' function on the main NFTY contract.");
}
function excludeFromRewards(address account) external onlyOwner {
require(!excludedFromRewards[account]);
excludedFromRewards[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromRewards(account);
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "claimWait must be updated to between 1 and 24 hours");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function minimumTokenLimit() public view returns(uint256) {
return minimumTokenBalanceForRewards;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableRewards,
uint256 totalRewards,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableRewards = withdrawableRewardOf(account);
totalRewards = accumulativeRewardOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromRewards[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForRewards) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawRewardOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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() {
_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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
} | @dev Internal function that mints tokens to an account. Update magnifiedRewardCorrections to keep rewards unchanged. @param account The account that will receive the created tokens. @param value The amount that will be created. | function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedRewardCorrections[account] = magnifiedRewardCorrections[account]
.sub( (magnifiedRewardPerShare.mul(value)).toInt256Safe() );
}
| 10,321,104 | [
1,
3061,
445,
716,
312,
28142,
2430,
358,
392,
2236,
18,
2315,
28160,
939,
17631,
1060,
20884,
87,
358,
3455,
283,
6397,
14827,
18,
225,
2236,
1021,
2236,
716,
903,
6798,
326,
2522,
2430,
18,
225,
460,
1021,
3844,
716,
903,
506,
2522,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
81,
474,
12,
2867,
2236,
16,
2254,
5034,
460,
13,
2713,
3849,
288,
203,
3639,
2240,
6315,
81,
474,
12,
4631,
16,
460,
1769,
203,
203,
3639,
28160,
939,
17631,
1060,
20884,
87,
63,
4631,
65,
273,
28160,
939,
17631,
1060,
20884,
87,
63,
4631,
65,
203,
3639,
263,
1717,
12,
261,
4527,
82,
939,
17631,
1060,
2173,
9535,
18,
16411,
12,
1132,
13,
2934,
869,
1702,
5034,
9890,
1435,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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 "../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 "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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 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;
/**
* @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;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {
IUniswapV3MintCallback
} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import {
IUniswapV3SwapCallback
} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import {ArrakisVaultV1Storage} from "./abstract/ArrakisVaultV1Storage.sol";
import {TickMath} from "./vendor/uniswap/TickMath.sol";
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {
FullMath,
LiquidityAmounts
} from "./vendor/uniswap/LiquidityAmounts.sol";
contract ArrakisVaultV1 is
IUniswapV3MintCallback,
IUniswapV3SwapCallback,
ArrakisVaultV1Storage
{
using SafeERC20 for IERC20;
using TickMath for int24;
event Minted(
address receiver,
uint256 mintAmount,
uint256 amount0In,
uint256 amount1In,
uint128 liquidityMinted
);
event Burned(
address receiver,
uint256 burnAmount,
uint256 amount0Out,
uint256 amount1Out,
uint128 liquidityBurned
);
event Rebalance(
int24 lowerTick_,
int24 upperTick_,
uint128 liquidityBefore,
uint128 liquidityAfter
);
event FeesEarned(uint256 feesEarned0, uint256 feesEarned1);
// solhint-disable-next-line max-line-length
constructor(address payable _gelato, address _arrakisTreasury)
ArrakisVaultV1Storage(_gelato, _arrakisTreasury)
{} // solhint-disable-line no-empty-blocks
/// @notice Uniswap V3 callback fn, called back on pool.mint
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata /*_data*/
) external override {
require(msg.sender == address(pool), "callback caller");
if (amount0Owed > 0) token0.safeTransfer(msg.sender, amount0Owed);
if (amount1Owed > 0) token1.safeTransfer(msg.sender, amount1Owed);
}
/// @notice Uniswap v3 callback fn, called back on pool.swap
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata /*data*/
) external override {
require(msg.sender == address(pool), "callback caller");
if (amount0Delta > 0)
token0.safeTransfer(msg.sender, uint256(amount0Delta));
else if (amount1Delta > 0)
token1.safeTransfer(msg.sender, uint256(amount1Delta));
}
// User functions => Should be called via a Router
/// @notice mint ArrakisVaultV1 Shares, fractional shares of a Uniswap V3 position/strategy
/// @dev to compute the amouint of tokens necessary to mint `mintAmount` see getMintAmounts
/// @param mintAmount The number of shares to mint
/// @param receiver The account to receive the minted shares
/// @return amount0 amount of token0 transferred from msg.sender to mint `mintAmount`
/// @return amount1 amount of token1 transferred from msg.sender to mint `mintAmount`
/// @return liquidityMinted amount of liquidity added to the underlying Uniswap V3 position
// solhint-disable-next-line function-max-lines, code-complexity
function mint(uint256 mintAmount, address receiver)
external
nonReentrant
returns (
uint256 amount0,
uint256 amount1,
uint128 liquidityMinted
)
{
require(mintAmount > 0, "mint 0");
require(
restrictedMintToggle != 11111 || msg.sender == _manager,
"restricted"
);
uint256 totalSupply = totalSupply();
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
if (totalSupply > 0) {
(uint256 amount0Current, uint256 amount1Current) =
getUnderlyingBalances();
amount0 = FullMath.mulDivRoundingUp(
amount0Current,
mintAmount,
totalSupply
);
amount1 = FullMath.mulDivRoundingUp(
amount1Current,
mintAmount,
totalSupply
);
} else {
// if supply is 0 mintAmount == liquidity to deposit
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
SafeCast.toUint128(mintAmount)
);
}
// transfer amounts owed to contract
if (amount0 > 0) {
token0.safeTransferFrom(msg.sender, address(this), amount0);
}
if (amount1 > 0) {
token1.safeTransferFrom(msg.sender, address(this), amount1);
}
// deposit as much new liquidity as possible
liquidityMinted = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
amount0,
amount1
);
pool.mint(address(this), lowerTick, upperTick, liquidityMinted, "");
_mint(receiver, mintAmount);
emit Minted(receiver, mintAmount, amount0, amount1, liquidityMinted);
}
/// @notice burn ArrakisVaultV1 Shares (shares of a Uniswap V3 position) and receive underlying
/// @param burnAmount The number of shares to burn
/// @param receiver The account to receive the underlying amounts of token0 and token1
/// @return amount0 amount of token0 transferred to receiver for burning `burnAmount`
/// @return amount1 amount of token1 transferred to receiver for burning `burnAmount`
/// @return liquidityBurned amount of liquidity removed from the underlying Uniswap V3 position
// solhint-disable-next-line function-max-lines
function burn(uint256 burnAmount, address receiver)
external
nonReentrant
returns (
uint256 amount0,
uint256 amount1,
uint128 liquidityBurned
)
{
require(burnAmount > 0, "burn 0");
uint256 totalSupply = totalSupply();
(uint128 liquidity, , , , ) = pool.positions(_getPositionID());
_burn(msg.sender, burnAmount);
uint256 liquidityBurned_ =
FullMath.mulDiv(burnAmount, liquidity, totalSupply);
liquidityBurned = SafeCast.toUint128(liquidityBurned_);
(uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1) =
_withdraw(lowerTick, upperTick, liquidityBurned);
_applyFees(fee0, fee1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
emit FeesEarned(fee0, fee1);
amount0 =
burn0 +
FullMath.mulDiv(
token0.balanceOf(address(this)) -
burn0 -
managerBalance0 -
arrakisBalance0,
burnAmount,
totalSupply
);
amount1 =
burn1 +
FullMath.mulDiv(
token1.balanceOf(address(this)) -
burn1 -
managerBalance1 -
arrakisBalance1,
burnAmount,
totalSupply
);
if (amount0 > 0) {
token0.safeTransfer(receiver, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(receiver, amount1);
}
emit Burned(receiver, burnAmount, amount0, amount1, liquidityBurned);
}
// Manager Functions => Called by Pool Manager
/// @notice Change the range of underlying UniswapV3 position, only manager can call
/// @dev When changing the range the inventory of token0 and token1 may be rebalanced
/// with a swap to deposit as much liquidity as possible into the new position. Swap parameters
/// can be computed by simulating the whole operation: remove all liquidity, deposit as much
/// as possible into new position, then observe how much of token0 or token1 is leftover.
/// Swap a proportion of this leftover to deposit more liquidity into the position, since
/// any leftover will be unused and sit idle until the next rebalance.
/// @param newLowerTick The new lower bound of the position's range
/// @param newUpperTick The new upper bound of the position's range
/// @param swapThresholdPrice slippage parameter on the swap as a max or min sqrtPriceX96
/// @param swapAmountBPS amount of token to swap as proportion of total. Pass 0 to ignore swap.
/// @param zeroForOne Which token to input into the swap (true = token0, false = token1)
// solhint-disable-next-line function-max-lines
function executiveRebalance(
int24 newLowerTick,
int24 newUpperTick,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne
) external onlyManager {
uint128 liquidity;
uint128 newLiquidity;
if (totalSupply() > 0) {
(liquidity, , , , ) = pool.positions(_getPositionID());
if (liquidity > 0) {
(, , uint256 fee0, uint256 fee1) =
_withdraw(lowerTick, upperTick, liquidity);
_applyFees(fee0, fee1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
emit FeesEarned(fee0, fee1);
}
lowerTick = newLowerTick;
upperTick = newUpperTick;
uint256 reinvest0 =
token0.balanceOf(address(this)) -
managerBalance0 -
arrakisBalance0;
uint256 reinvest1 =
token1.balanceOf(address(this)) -
managerBalance1 -
arrakisBalance1;
_deposit(
newLowerTick,
newUpperTick,
reinvest0,
reinvest1,
swapThresholdPrice,
swapAmountBPS,
zeroForOne
);
(newLiquidity, , , , ) = pool.positions(_getPositionID());
require(newLiquidity > 0, "new position 0");
} else {
lowerTick = newLowerTick;
upperTick = newUpperTick;
}
emit Rebalance(newLowerTick, newUpperTick, liquidity, newLiquidity);
}
// Gelatofied functions => Automatically called by Gelato
/// @notice Reinvest fees earned into underlying position, only gelato executors can call
/// Position bounds CANNOT be altered by gelato, only manager may via executiveRebalance.
/// Frequency of rebalance configured with gelatoRebalanceBPS, alterable by manager.
function rebalance(
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne,
uint256 feeAmount,
address paymentToken
) external gelatofy(feeAmount, paymentToken) {
if (swapAmountBPS > 0) {
_checkSlippage(swapThresholdPrice, zeroForOne);
}
(uint128 liquidity, , , , ) = pool.positions(_getPositionID());
_rebalance(
liquidity,
swapThresholdPrice,
swapAmountBPS,
zeroForOne,
feeAmount,
paymentToken
);
(uint128 newLiquidity, , , , ) = pool.positions(_getPositionID());
require(newLiquidity > liquidity, "liquidity must increase");
emit Rebalance(lowerTick, upperTick, liquidity, newLiquidity);
}
/// @notice withdraw manager fees accrued
function withdrawManagerBalance() external {
uint256 amount0 = managerBalance0;
uint256 amount1 = managerBalance1;
managerBalance0 = 0;
managerBalance1 = 0;
if (amount0 > 0) {
token0.safeTransfer(managerTreasury, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(managerTreasury, amount1);
}
}
/// @notice withdraw arrakis fees accrued
function withdrawArrakisBalance() external {
uint256 amount0 = arrakisBalance0;
uint256 amount1 = arrakisBalance1;
arrakisBalance0 = 0;
arrakisBalance1 = 0;
if (amount0 > 0) {
token0.safeTransfer(arrakisTreasury, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(arrakisTreasury, amount1);
}
}
// View functions
/// @notice compute maximum shares that can be minted from `amount0Max` and `amount1Max`
/// @param amount0Max The maximum amount of token0 to forward on mint
/// @param amount0Max The maximum amount of token1 to forward on mint
/// @return amount0 actual amount of token0 to forward when minting `mintAmount`
/// @return amount1 actual amount of token1 to forward when minting `mintAmount`
/// @return mintAmount maximum number of shares mintable
function getMintAmounts(uint256 amount0Max, uint256 amount1Max)
external
view
returns (
uint256 amount0,
uint256 amount1,
uint256 mintAmount
)
{
uint256 totalSupply = totalSupply();
if (totalSupply > 0) {
(amount0, amount1, mintAmount) = _computeMintAmounts(
totalSupply,
amount0Max,
amount1Max
);
} else {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint128 newLiquidity =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
amount0Max,
amount1Max
);
mintAmount = uint256(newLiquidity);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
newLiquidity
);
}
}
/// @notice compute total underlying holdings of the G-UNI token supply
/// includes current liquidity invested in uniswap position, current fees earned
/// and any uninvested leftover (but does not include manager or gelato fees accrued)
/// @return amount0Current current total underlying balance of token0
/// @return amount1Current current total underlying balance of token1
function getUnderlyingBalances()
public
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(uint160 sqrtRatioX96, int24 tick, , , , , ) = pool.slot0();
return _getUnderlyingBalances(sqrtRatioX96, tick);
}
function getUnderlyingBalancesAtPrice(uint160 sqrtRatioX96)
external
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(, int24 tick, , , , , ) = pool.slot0();
return _getUnderlyingBalances(sqrtRatioX96, tick);
}
// solhint-disable-next-line function-max-lines
function _getUnderlyingBalances(uint160 sqrtRatioX96, int24 tick)
internal
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(
uint128 liquidity,
uint256 feeGrowthInside0Last,
uint256 feeGrowthInside1Last,
uint128 tokensOwed0,
uint128 tokensOwed1
) = pool.positions(_getPositionID());
// compute current holdings from liquidity
(amount0Current, amount1Current) = LiquidityAmounts
.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
liquidity
);
// compute current fees earned
uint256 fee0 =
_computeFeesEarned(true, feeGrowthInside0Last, tick, liquidity) +
uint256(tokensOwed0);
uint256 fee1 =
_computeFeesEarned(false, feeGrowthInside1Last, tick, liquidity) +
uint256(tokensOwed1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
// add any leftover in contract to current holdings
amount0Current +=
fee0 +
token0.balanceOf(address(this)) -
managerBalance0 -
arrakisBalance0;
amount1Current +=
fee1 +
token1.balanceOf(address(this)) -
managerBalance1 -
arrakisBalance1;
}
// Private functions
// solhint-disable-next-line function-max-lines
function _rebalance(
uint128 liquidity,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne,
uint256 feeAmount,
address paymentToken
) private {
uint256 leftover0 =
token0.balanceOf(address(this)) - managerBalance0 - arrakisBalance0;
uint256 leftover1 =
token1.balanceOf(address(this)) - managerBalance1 - arrakisBalance1;
(, , uint256 feesEarned0, uint256 feesEarned1) =
_withdraw(lowerTick, upperTick, liquidity);
_applyFees(feesEarned0, feesEarned1);
(feesEarned0, feesEarned1) = _subtractAdminFees(
feesEarned0,
feesEarned1
);
emit FeesEarned(feesEarned0, feesEarned1);
feesEarned0 += leftover0;
feesEarned1 += leftover1;
if (paymentToken == address(token0)) {
require(
(feesEarned0 * gelatoRebalanceBPS) / 10000 >= feeAmount,
"high fee"
);
leftover0 =
token0.balanceOf(address(this)) -
managerBalance0 -
arrakisBalance0 -
feeAmount;
leftover1 =
token1.balanceOf(address(this)) -
managerBalance1 -
arrakisBalance1;
} else if (paymentToken == address(token1)) {
require(
(feesEarned1 * gelatoRebalanceBPS) / 10000 >= feeAmount,
"high fee"
);
leftover0 =
token0.balanceOf(address(this)) -
managerBalance0 -
arrakisBalance0;
leftover1 =
token1.balanceOf(address(this)) -
managerBalance1 -
arrakisBalance1 -
feeAmount;
} else {
revert("wrong token");
}
_deposit(
lowerTick,
upperTick,
leftover0,
leftover1,
swapThresholdPrice,
swapAmountBPS,
zeroForOne
);
}
// solhint-disable-next-line function-max-lines
function _withdraw(
int24 lowerTick_,
int24 upperTick_,
uint128 liquidity
)
private
returns (
uint256 burn0,
uint256 burn1,
uint256 fee0,
uint256 fee1
)
{
uint256 preBalance0 = token0.balanceOf(address(this));
uint256 preBalance1 = token1.balanceOf(address(this));
(burn0, burn1) = pool.burn(lowerTick_, upperTick_, liquidity);
pool.collect(
address(this),
lowerTick_,
upperTick_,
type(uint128).max,
type(uint128).max
);
fee0 = token0.balanceOf(address(this)) - preBalance0 - burn0;
fee1 = token1.balanceOf(address(this)) - preBalance1 - burn1;
}
// solhint-disable-next-line function-max-lines
function _deposit(
int24 lowerTick_,
int24 upperTick_,
uint256 amount0,
uint256 amount1,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne
) private {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
// First, deposit as much as we can
uint128 baseLiquidity =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick_.getSqrtRatioAtTick(),
upperTick_.getSqrtRatioAtTick(),
amount0,
amount1
);
if (baseLiquidity > 0) {
(uint256 amountDeposited0, uint256 amountDeposited1) =
pool.mint(
address(this),
lowerTick_,
upperTick_,
baseLiquidity,
""
);
amount0 -= amountDeposited0;
amount1 -= amountDeposited1;
}
int256 swapAmount =
SafeCast.toInt256(
((zeroForOne ? amount0 : amount1) * swapAmountBPS) / 10000
);
if (swapAmount > 0) {
_swapAndDeposit(
lowerTick_,
upperTick_,
amount0,
amount1,
swapAmount,
swapThresholdPrice,
zeroForOne
);
}
}
function _swapAndDeposit(
int24 lowerTick_,
int24 upperTick_,
uint256 amount0,
uint256 amount1,
int256 swapAmount,
uint160 swapThresholdPrice,
bool zeroForOne
) private returns (uint256 finalAmount0, uint256 finalAmount1) {
(int256 amount0Delta, int256 amount1Delta) =
pool.swap(
address(this),
zeroForOne,
swapAmount,
swapThresholdPrice,
""
);
finalAmount0 = uint256(SafeCast.toInt256(amount0) - amount0Delta);
finalAmount1 = uint256(SafeCast.toInt256(amount1) - amount1Delta);
// Add liquidity a second time
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint128 liquidityAfterSwap =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick_.getSqrtRatioAtTick(),
upperTick_.getSqrtRatioAtTick(),
finalAmount0,
finalAmount1
);
if (liquidityAfterSwap > 0) {
pool.mint(
address(this),
lowerTick_,
upperTick_,
liquidityAfterSwap,
""
);
}
}
// solhint-disable-next-line function-max-lines, code-complexity
function _computeMintAmounts(
uint256 totalSupply,
uint256 amount0Max,
uint256 amount1Max
)
private
view
returns (
uint256 amount0,
uint256 amount1,
uint256 mintAmount
)
{
(uint256 amount0Current, uint256 amount1Current) =
getUnderlyingBalances();
// compute proportional amount of tokens to mint
if (amount0Current == 0 && amount1Current > 0) {
mintAmount = FullMath.mulDiv(
amount1Max,
totalSupply,
amount1Current
);
} else if (amount1Current == 0 && amount0Current > 0) {
mintAmount = FullMath.mulDiv(
amount0Max,
totalSupply,
amount0Current
);
} else if (amount0Current == 0 && amount1Current == 0) {
revert("");
} else {
// only if both are non-zero
uint256 amount0Mint =
FullMath.mulDiv(amount0Max, totalSupply, amount0Current);
uint256 amount1Mint =
FullMath.mulDiv(amount1Max, totalSupply, amount1Current);
require(amount0Mint > 0 && amount1Mint > 0, "mint 0");
mintAmount = amount0Mint < amount1Mint ? amount0Mint : amount1Mint;
}
// compute amounts owed to contract
amount0 = FullMath.mulDivRoundingUp(
mintAmount,
amount0Current,
totalSupply
);
amount1 = FullMath.mulDivRoundingUp(
mintAmount,
amount1Current,
totalSupply
);
}
// solhint-disable-next-line function-max-lines
function _computeFeesEarned(
bool isZero,
uint256 feeGrowthInsideLast,
int24 tick,
uint128 liquidity
) private view returns (uint256 fee) {
uint256 feeGrowthOutsideLower;
uint256 feeGrowthOutsideUpper;
uint256 feeGrowthGlobal;
if (isZero) {
feeGrowthGlobal = pool.feeGrowthGlobal0X128();
(, , feeGrowthOutsideLower, , , , , ) = pool.ticks(lowerTick);
(, , feeGrowthOutsideUpper, , , , , ) = pool.ticks(upperTick);
} else {
feeGrowthGlobal = pool.feeGrowthGlobal1X128();
(, , , feeGrowthOutsideLower, , , , ) = pool.ticks(lowerTick);
(, , , feeGrowthOutsideUpper, , , , ) = pool.ticks(upperTick);
}
unchecked {
// calculate fee growth below
uint256 feeGrowthBelow;
if (tick >= lowerTick) {
feeGrowthBelow = feeGrowthOutsideLower;
} else {
feeGrowthBelow = feeGrowthGlobal - feeGrowthOutsideLower;
}
// calculate fee growth above
uint256 feeGrowthAbove;
if (tick < upperTick) {
feeGrowthAbove = feeGrowthOutsideUpper;
} else {
feeGrowthAbove = feeGrowthGlobal - feeGrowthOutsideUpper;
}
uint256 feeGrowthInside =
feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove;
fee = FullMath.mulDiv(
liquidity,
feeGrowthInside - feeGrowthInsideLast,
0x100000000000000000000000000000000
);
}
}
function _applyFees(uint256 _fee0, uint256 _fee1) private {
arrakisBalance0 += (_fee0 * arrakisFeeBPS) / 10000;
arrakisBalance1 += (_fee1 * arrakisFeeBPS) / 10000;
managerBalance0 += (_fee0 * managerFeeBPS) / 10000;
managerBalance1 += (_fee1 * managerFeeBPS) / 10000;
}
function _subtractAdminFees(uint256 rawFee0, uint256 rawFee1)
private
view
returns (uint256 fee0, uint256 fee1)
{
uint256 deduct0 = (rawFee0 * (arrakisFeeBPS + managerFeeBPS)) / 10000;
uint256 deduct1 = (rawFee1 * (arrakisFeeBPS + managerFeeBPS)) / 10000;
fee0 = rawFee0 - deduct0;
fee1 = rawFee1 - deduct1;
}
function _checkSlippage(uint160 swapThresholdPrice, bool zeroForOne)
private
view
{
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = gelatoSlippageInterval;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
require(tickCumulatives.length == 2, "array len");
uint160 avgSqrtRatioX96;
unchecked {
int24 avgTick =
int24(
(tickCumulatives[1] - tickCumulatives[0]) /
int56(uint56(gelatoSlippageInterval))
);
avgSqrtRatioX96 = avgTick.getSqrtRatioAtTick();
}
uint160 maxSlippage = (avgSqrtRatioX96 * gelatoSlippageBPS) / 10000;
if (zeroForOne) {
require(
swapThresholdPrice >= avgSqrtRatioX96 - maxSlippage,
"high slippage"
);
} else {
require(
swapThresholdPrice <= avgSqrtRatioX96 + maxSlippage,
"high slippage"
);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {Gelatofied} from "./Gelatofied.sol";
import {OwnableUninitialized} from "./OwnableUninitialized.sol";
import {
IUniswapV3Pool
} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
/// @dev Single Global upgradeable state var storage base: APPEND ONLY
/// @dev Add all inherited contracts with state vars here: APPEND ONLY
/// @dev ERC20Upgradable Includes Initialize
// solhint-disable-next-line max-states-count
abstract contract ArrakisVaultV1Storage is
ERC20Upgradeable, /* XXXX DONT MODIFY ORDERING XXXX */
ReentrancyGuardUpgradeable,
OwnableUninitialized,
Gelatofied
// APPEND ADDITIONAL BASE WITH STATE VARS BELOW:
// XXXX DONT MODIFY ORDERING XXXX
{
// solhint-disable-next-line const-name-snakecase
string public constant version = "1.0.0";
// solhint-disable-next-line const-name-snakecase
uint16 public constant arrakisFeeBPS = 250;
/// @dev "restricted mint enabled" toggle value must be a number
// above 10000 to safely avoid collisions for repurposed state var
uint16 public constant RESTRICTED_MINT_ENABLED = 11111;
address public immutable arrakisTreasury;
// XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX
int24 public lowerTick;
int24 public upperTick;
uint16 public gelatoRebalanceBPS;
uint16 public restrictedMintToggle;
uint16 public gelatoSlippageBPS;
uint32 public gelatoSlippageInterval;
uint16 public managerFeeBPS;
address public managerTreasury;
uint256 public managerBalance0;
uint256 public managerBalance1;
uint256 public arrakisBalance0;
uint256 public arrakisBalance1;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
// APPPEND ADDITIONAL STATE VARS BELOW:
// XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX
event UpdateManagerParams(
uint16 managerFeeBPS,
address managerTreasury,
uint16 gelatoRebalanceBPS,
uint16 gelatoSlippageBPS,
uint32 gelatoSlippageInterval
);
// solhint-disable-next-line max-line-length
constructor(address payable _gelato, address _arrakisTreasury)
Gelatofied(_gelato)
{
arrakisTreasury = _arrakisTreasury;
}
/// @notice initialize storage variables on a new G-UNI pool, only called once
/// @param _name name of Vault (immutable)
/// @param _symbol symbol of Vault (immutable)
/// @param _pool address of Uniswap V3 pool (immutable)
/// @param _managerFeeBPS proportion of fees earned that go to manager treasury
/// @param _lowerTick initial lowerTick (only changeable with executiveRebalance)
/// @param _lowerTick initial upperTick (only changeable with executiveRebalance)
/// @param _manager_ address of manager (ownership can be transferred)
function initialize(
string memory _name,
string memory _symbol,
address _pool,
uint16 _managerFeeBPS,
int24 _lowerTick,
int24 _upperTick,
address _manager_
) external initializer {
require(_managerFeeBPS <= 10000 - arrakisFeeBPS, "mBPS");
// these variables are immutable after initialization
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
// these variables can be udpated by the manager
_manager = _manager_;
managerFeeBPS = _managerFeeBPS;
managerTreasury = _manager_; // default: treasury is admin
gelatoSlippageInterval = 5 minutes; // default: last five minutes;
gelatoSlippageBPS = 500; // default: 5% slippage
gelatoRebalanceBPS = 200; // default: only rebalance if tx fee is lt 2% reinvested
lowerTick = _lowerTick;
upperTick = _upperTick;
// e.g. "Gelato Uniswap V3 USDC/DAI LP" and "G-UNI"
__ERC20_init(_name, _symbol);
__ReentrancyGuard_init();
}
/// @notice change configurable gelato parameters, only manager can call
/// @param newManagerFeeBPS Basis Points of fees earned credited to manager (negative to ignore)
/// @param newManagerTreasury address that collects manager fees (Zero address to ignore)
/// @param newRebalanceBPS threshold fees earned for gelato rebalances (negative to ignore)
/// @param newSlippageBPS frontrun protection parameter (negative to ignore)
/// @param newSlippageInterval frontrun protection parameter (negative to ignore)
// solhint-disable-next-line code-complexity
function updateManagerParams(
int16 newManagerFeeBPS,
address newManagerTreasury,
int16 newRebalanceBPS,
int16 newSlippageBPS,
int32 newSlippageInterval
) external onlyManager {
require(newRebalanceBPS <= 10000, "BPS");
require(newSlippageBPS <= 10000, "BPS");
require(newManagerFeeBPS <= 10000 - int16(arrakisFeeBPS), "mBPS");
if (newManagerFeeBPS >= 0) managerFeeBPS = uint16(newManagerFeeBPS);
if (newRebalanceBPS >= 0) gelatoRebalanceBPS = uint16(newRebalanceBPS);
if (newSlippageBPS >= 0) gelatoSlippageBPS = uint16(newSlippageBPS);
if (newSlippageInterval >= 0)
gelatoSlippageInterval = uint32(newSlippageInterval);
if (address(0) != newManagerTreasury)
managerTreasury = newManagerTreasury;
emit UpdateManagerParams(
managerFeeBPS,
managerTreasury,
gelatoRebalanceBPS,
gelatoSlippageBPS,
gelatoSlippageInterval
);
}
function toggleRestrictMint() external onlyManager {
if (restrictedMintToggle == RESTRICTED_MINT_ENABLED) {
restrictedMintToggle = 0;
} else {
restrictedMintToggle = RESTRICTED_MINT_ENABLED;
}
}
function renounceOwnership() public virtual override onlyManager {
managerTreasury = address(0);
managerFeeBPS = 0;
managerBalance0 = 0;
managerBalance1 = 0;
super.renounceOwnership();
}
function getPositionID() external view returns (bytes32 positionID) {
return _getPositionID();
}
function _getPositionID() internal view returns (bytes32 positionID) {
return keccak256(abi.encodePacked(address(this), lowerTick, upperTick));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @dev DO NOT ADD STATE VARIABLES - APPEND THEM TO GelatoUniV3PoolStorage
/// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS - APPEND THEM TO GelatoUniV3PoolStorage
abstract contract Gelatofied {
using Address for address payable;
using SafeERC20 for IERC20;
// solhint-disable-next-line var-name-mixedcase
address payable public immutable GELATO;
address private constant _ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(address payable _gelato) {
GELATO = _gelato;
}
modifier gelatofy(uint256 _amount, address _paymentToken) {
require(msg.sender == GELATO, "Gelatofied: Only gelato");
_;
if (_paymentToken == _ETH) GELATO.sendValue(_amount);
else IERC20(_paymentToken).safeTransfer(GELATO, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an manager) that can be granted exclusive access to
* specific functions.
*
* By default, the manager 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
* `onlyManager`, which can be applied to your functions to restrict their use to
* the manager.
*/
/// @dev DO NOT ADD STATE VARIABLES - APPEND THEM TO GelatoUniV3PoolStorage
/// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS - APPEND THEM TO GelatoUniV3PoolStorage
abstract contract OwnableUninitialized {
address internal _manager;
event OwnershipTransferred(
address indexed previousManager,
address indexed newManager
);
/// @dev Initializes the contract setting the deployer as the initial manager.
/// CONSTRUCTOR EMPTY - USE INITIALIZIABLE INSTEAD
// solhint-disable-next-line no-empty-blocks
constructor() {}
/**
* @dev Returns the address of the current manager.
*/
function manager() public view virtual returns (address) {
return _manager;
}
/**
* @dev Throws if called by any account other than the manager.
*/
modifier onlyManager() {
require(manager() == msg.sender, "Ownable: caller is not the manager");
_;
}
/**
* @dev Leaves the contract without manager. It will not be possible to call
* `onlyManager` functions anymore. Can only be called by the current manager.
*
* NOTE: Renouncing ownership will leave the contract without an manager,
* thereby removing any functionality that is only available to the manager.
*/
function renounceOwnership() public virtual onlyManager {
emit OwnershipTransferred(_manager, address(0));
_manager = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current manager.
*/
function transferOwnership(address newOwner) public virtual onlyManager {
require(
newOwner != address(0),
"Ownable: new manager is the zero address"
);
emit OwnershipTransferred(_manager, newOwner);
_manager = newOwner;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then 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(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
// EDIT for 0.8 compatibility:
// see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// 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
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use 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.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // 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 precoditions 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 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
import {FullMath} from "./FullMath.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate =
FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return
toUint128(
FullMath.mulDiv(
amount0,
intermediate,
sqrtRatioBX96 - sqrtRatioAX96
)
);
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
toUint128(
FullMath.mulDiv(
amount1,
FixedPoint96.Q96,
sqrtRatioBX96 - sqrtRatioAX96
)
);
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(
sqrtRatioAX96,
sqrtRatioBX96,
amount0
);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 =
getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 =
getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(
sqrtRatioAX96,
sqrtRatioBX96,
amount1
);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The liquidity being valued
/// @return amount0 The amount0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The liquidity being valued
/// @return amount1 The amount1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
liquidity,
sqrtRatioBX96 - sqrtRatioAX96,
FixedPoint96.Q96
);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(
sqrtRatioX96,
sqrtRatioBX96,
liquidity
);
amount1 = getAmount1ForLiquidity(
sqrtRatioAX96,
sqrtRatioX96,
liquidity
);
} else {
amount1 = getAmount1ForLiquidity(
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO =
1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick)
internal
pure
returns (uint160 sqrtPriceX96)
{
uint256 absTick =
tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
// EDIT: 0.8 compatibility
require(absTick <= uint256(int256(MAX_TICK)), "T");
uint256 ratio =
absTick & 0x1 != 0
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0)
ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0)
ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0)
ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0)
ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0)
ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0)
ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0)
ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0)
ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0)
ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0)
ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0)
ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0)
ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0)
ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0)
ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0)
ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0)
ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0)
ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0)
ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0)
ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160(
(ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)
);
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96)
internal
pure
returns (int24 tick)
{
// second inequality must be < because the price can never reach the price at the max tick
require(
sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,
"R"
);
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow =
int24(
(log_sqrt10001 - 3402992956809132418596140100660247210) >> 128
);
int24 tickHi =
int24(
(log_sqrt10001 + 291339464771989622907027621153398088495) >> 128
);
tick = tickLow == tickHi
? tickLow
: getSqrtRatioAtTick(tickHi) <= sqrtPriceX96
? tickHi
: tickLow;
}
} | @notice change configurable gelato parameters, only manager can call @param newManagerFeeBPS Basis Points of fees earned credited to manager (negative to ignore) @param newManagerTreasury address that collects manager fees (Zero address to ignore) @param newRebalanceBPS threshold fees earned for gelato rebalances (negative to ignore) @param newSlippageBPS frontrun protection parameter (negative to ignore) @param newSlippageInterval frontrun protection parameter (negative to ignore) solhint-disable-next-line code-complexity | function updateManagerParams(
int16 newManagerFeeBPS,
address newManagerTreasury,
int16 newRebalanceBPS,
int16 newSlippageBPS,
int32 newSlippageInterval
) external onlyManager {
require(newRebalanceBPS <= 10000, "BPS");
require(newSlippageBPS <= 10000, "BPS");
require(newManagerFeeBPS <= 10000 - int16(arrakisFeeBPS), "mBPS");
if (newManagerFeeBPS >= 0) managerFeeBPS = uint16(newManagerFeeBPS);
if (newRebalanceBPS >= 0) gelatoRebalanceBPS = uint16(newRebalanceBPS);
if (newSlippageBPS >= 0) gelatoSlippageBPS = uint16(newSlippageBPS);
if (newSlippageInterval >= 0)
gelatoSlippageInterval = uint32(newSlippageInterval);
if (address(0) != newManagerTreasury)
managerTreasury = newManagerTreasury;
emit UpdateManagerParams(
managerFeeBPS,
managerTreasury,
gelatoRebalanceBPS,
gelatoSlippageBPS,
gelatoSlippageInterval
);
}
| 14,726,205 | [
1,
3427,
14593,
314,
292,
31093,
1472,
16,
1338,
3301,
848,
745,
225,
394,
1318,
14667,
38,
5857,
605,
17247,
22464,
434,
1656,
281,
425,
1303,
329,
12896,
329,
358,
3301,
261,
13258,
358,
2305,
13,
225,
394,
1318,
56,
266,
345,
22498,
1758,
716,
30976,
3301,
1656,
281,
261,
7170,
1758,
358,
2305,
13,
225,
394,
426,
12296,
38,
5857,
5573,
1656,
281,
425,
1303,
329,
364,
314,
292,
31093,
283,
70,
26488,
261,
13258,
358,
2305,
13,
225,
30826,
3169,
2433,
38,
5857,
284,
1949,
313,
318,
17862,
1569,
261,
13258,
358,
2305,
13,
225,
30826,
3169,
2433,
4006,
284,
1949,
313,
318,
17862,
1569,
261,
13258,
358,
2305,
13,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
981,
17,
14259,
560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
1318,
1370,
12,
203,
3639,
509,
2313,
394,
1318,
14667,
38,
5857,
16,
203,
3639,
1758,
394,
1318,
56,
266,
345,
22498,
16,
203,
3639,
509,
2313,
394,
426,
12296,
38,
5857,
16,
203,
3639,
509,
2313,
30826,
3169,
2433,
38,
5857,
16,
203,
3639,
509,
1578,
30826,
3169,
2433,
4006,
203,
565,
262,
3903,
1338,
1318,
288,
203,
3639,
2583,
12,
2704,
426,
12296,
38,
5857,
1648,
12619,
16,
315,
38,
5857,
8863,
203,
3639,
2583,
12,
2704,
55,
3169,
2433,
38,
5857,
1648,
12619,
16,
315,
38,
5857,
8863,
203,
3639,
2583,
12,
2704,
1318,
14667,
38,
5857,
1648,
12619,
300,
509,
2313,
12,
297,
354,
79,
291,
14667,
38,
5857,
3631,
315,
81,
38,
5857,
8863,
203,
3639,
309,
261,
2704,
1318,
14667,
38,
5857,
1545,
374,
13,
3301,
14667,
38,
5857,
273,
2254,
2313,
12,
2704,
1318,
14667,
38,
5857,
1769,
203,
3639,
309,
261,
2704,
426,
12296,
38,
5857,
1545,
374,
13,
314,
292,
31093,
426,
12296,
38,
5857,
273,
2254,
2313,
12,
2704,
426,
12296,
38,
5857,
1769,
203,
3639,
309,
261,
2704,
55,
3169,
2433,
38,
5857,
1545,
374,
13,
314,
292,
31093,
55,
3169,
2433,
38,
5857,
273,
2254,
2313,
12,
2704,
55,
3169,
2433,
38,
5857,
1769,
203,
3639,
309,
261,
2704,
55,
3169,
2433,
4006,
1545,
374,
13,
203,
5411,
314,
292,
31093,
55,
3169,
2433,
4006,
273,
2254,
1578,
12,
2704,
55,
3169,
2433,
4006,
1769,
203,
3639,
309,
261,
2867,
12,
20,
13,
480,
394,
1318,
56,
266,
345,
2
] |
./partial_match/5/0x9e0861844F40B48207e6c5D384D53Dfe27f4a8EC/sources/DeporRPOSValidatorData.sol | stop runningstatus descriptionstatus = 0, createdstatus = 1, pausestatus = 2, runningstatus = 3, destroyed | function creatorPauseRuningValidator(address creator, uint256 vID)
external
whenNotPaused
onlyWhitelistAdmin
{
Validator storage validator = idToValidators[vID];
validator.status = 1;
runningValidatorCount--;
}
| 16,833,348 | [
1,
5681,
3549,
2327,
2477,
2327,
273,
374,
16,
2522,
2327,
273,
404,
16,
6790,
407,
395,
996,
273,
576,
16,
3549,
2327,
273,
890,
16,
17689,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11784,
19205,
1997,
310,
5126,
12,
2867,
11784,
16,
2254,
5034,
331,
734,
13,
203,
3639,
3903,
203,
3639,
1347,
1248,
28590,
203,
3639,
1338,
18927,
4446,
203,
565,
288,
203,
203,
3639,
9150,
2502,
4213,
273,
612,
774,
19420,
63,
90,
734,
15533,
203,
3639,
4213,
18,
2327,
273,
404,
31,
203,
203,
3639,
3549,
5126,
1380,
413,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.8;
import "../libraries/VersionUtils.sol";
import "../libraries/Util.sol";
import "../interfaces/IModule.sol";
import "../interfaces/IOracle.sol";
import "../interfaces/IPolymathRegistry.sol";
import "../interfaces/IModuleFactory.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../libraries/DecimalMath.sol";
/**
* @title Interface that any module factory contract should implement
* @notice Contract is abstract
*/
contract ModuleFactory is IModuleFactory, Ownable {
IPolymathRegistry public polymathRegistry;
string initialVersion;
bytes32 public name;
string public title;
string public description;
uint8[] typesData;
bytes32[] tagsData;
bool public isCostInPoly;
uint256 public setupCost;
string constant POLY_ORACLE = "StablePolyUsdOracle";
// @notice Allow only two variables to be stored
// 1. lowerBound
// 2. upperBound
// @dev (0.0.0 will act as the wildcard)
// @dev uint24 consists packed value of uint8 _major, uint8 _minor, uint8 _patch
mapping(string => uint24) compatibleSTVersionRange;
/**
* @notice Constructor
*/
constructor(uint256 _setupCost, address _polymathRegistry, bool _isCostInPoly) public {
setupCost = _setupCost;
polymathRegistry = IPolymathRegistry(_polymathRegistry);
isCostInPoly = _isCostInPoly;
}
/**
* @notice Type of the Module factory
*/
function getTypes() external view returns(uint8[] memory) {
return typesData;
}
/**
* @notice Get the tags related to the module factory
*/
function getTags() external view returns(bytes32[] memory) {
return tagsData;
}
/**
* @notice Get the version related to the module factory
*/
function version() external view returns(string memory) {
return initialVersion;
}
/**
* @notice Used to change the fee of the setup cost
* @param _setupCost new setup cost
*/
function changeSetupCost(uint256 _setupCost) public onlyOwner {
emit ChangeSetupCost(setupCost, _setupCost);
setupCost = _setupCost;
}
/**
* @notice Used to change the currency and amount of setup cost
* @param _setupCost new setup cost
* @param _isCostInPoly new setup cost currency. USD or POLY
*/
function changeCostAndType(uint256 _setupCost, bool _isCostInPoly) public onlyOwner {
emit ChangeSetupCost(setupCost, _setupCost);
emit ChangeCostType(isCostInPoly, _isCostInPoly);
setupCost = _setupCost;
isCostInPoly = _isCostInPoly;
}
/**
* @notice Updates the title of the ModuleFactory
* @param _title New Title that will replace the old one.
*/
function changeTitle(string memory _title) public onlyOwner {
require(bytes(_title).length > 0, "Invalid text");
title = _title;
}
/**
* @notice Updates the description of the ModuleFactory
* @param _description New description that will replace the old one.
*/
function changeDescription(string memory _description) public onlyOwner {
require(bytes(_description).length > 0, "Invalid text");
description = _description;
}
/**
* @notice Updates the name of the ModuleFactory
* @param _name New name that will replace the old one.
*/
function changeName(bytes32 _name) public onlyOwner {
require(_name != bytes32(0), "Invalid text");
name = _name;
}
/**
* @notice Updates the tags of the ModuleFactory
* @param _tagsData New list of tags
*/
function changeTags(bytes32[] memory _tagsData) public onlyOwner {
require(_tagsData.length > 0, "Invalid text");
tagsData = _tagsData;
}
/**
* @notice Function use to change the lower and upper bound of the compatible version st
* @param _boundType Type of bound
* @param _newVersion new version array
*/
function changeSTVersionBounds(string calldata _boundType, uint8[] calldata _newVersion) external onlyOwner {
require(
keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) || keccak256(
abi.encodePacked(_boundType)
) == keccak256(abi.encodePacked("upperBound")),
"Invalid bound type"
);
require(_newVersion.length == 3, "Invalid version");
if (compatibleSTVersionRange[_boundType] != uint24(0)) {
uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]);
if (keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound"))) {
require(VersionUtils.lessThanOrEqual(_newVersion, _currentVersion), "Invalid version");
} else {
require(VersionUtils.greaterThanOrEqual(_newVersion, _currentVersion), "Invalid version");
}
}
compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]);
emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]);
}
/**
* @notice Used to get the lower bound
* @return lower bound
*/
function getLowerSTVersionBounds() external view returns(uint8[] memory) {
return VersionUtils.unpack(compatibleSTVersionRange["lowerBound"]);
}
/**
* @notice Used to get the upper bound
* @return upper bound
*/
function getUpperSTVersionBounds() external view returns(uint8[] memory) {
return VersionUtils.unpack(compatibleSTVersionRange["upperBound"]);
}
/**
* @notice Get the setup cost of the module
*/
function setupCostInPoly() public returns (uint256) {
if (isCostInPoly)
return setupCost;
uint256 polyRate = IOracle(polymathRegistry.getAddress(POLY_ORACLE)).getPrice();
return DecimalMath.div(setupCost, polyRate);
}
/**
* @notice Calculates fee in POLY
*/
function _takeFee() internal returns(uint256) {
uint256 polySetupCost = setupCostInPoly();
address polyToken = polymathRegistry.getAddress("PolyToken");
if (polySetupCost > 0) {
require(IERC20(polyToken).transferFrom(msg.sender, owner(), polySetupCost), "Insufficient allowance for module fee");
}
return polySetupCost;
}
/**
* @notice Used to initialize the module
* @param _module Address of module
* @param _data Data used for the intialization of the module factory variables
*/
function _initializeModule(address _module, bytes memory _data) internal {
uint256 polySetupCost = _takeFee();
bytes4 initFunction = IModule(_module).getInitFunction();
if (initFunction != bytes4(0)) {
require(Util.getSig(_data) == initFunction, "Provided data is not valid");
/*solium-disable-next-line security/no-low-level-calls*/
(bool success, ) = _module.call(_data);
require(success, "Unsuccessful initialization");
}
/*solium-disable-next-line security/no-block-members*/
emit GenerateModuleFromFactory(_module, name, address(this), msg.sender, setupCost, polySetupCost);
}
}
| * @notice Used to change the fee of the setup cost @param _setupCost new setup cost/ | function changeSetupCost(uint256 _setupCost) public onlyOwner {
emit ChangeSetupCost(setupCost, _setupCost);
setupCost = _setupCost;
}
| 12,850,205 | [
1,
6668,
358,
2549,
326,
14036,
434,
326,
3875,
6991,
225,
389,
8401,
8018,
394,
3875,
6991,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2549,
7365,
8018,
12,
11890,
5034,
389,
8401,
8018,
13,
1071,
1338,
5541,
288,
203,
3639,
3626,
7576,
7365,
8018,
12,
8401,
8018,
16,
389,
8401,
8018,
1769,
203,
3639,
3875,
8018,
273,
389,
8401,
8018,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xb978A5F4854274bc5196bC2a4633863CB3A0a6b7
//Contract name: Pyramid
//Balance: 0.106 Ether
//Verification Date: 6/14/2017
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity ^0.4.0;
contract Pyramid {
address master;
address[] memberQueue;
uint queueFront;
event Joined(address indexed _member, uint _entries, uint _paybackStartNum);
modifier onlymaster { if (msg.sender == master) _; }
function Pyramid() {
master = msg.sender;
memberQueue.push(master);
queueFront = 0;
}
// fallback function, wont work to call join here bc we will run out of gas (2300 gas for send())
function(){}
// users are allowed to join with .1 - 5 ethereum
function join() payable {
require(msg.value >= 100 finney);
uint entries = msg.value / 100 finney;
entries = entries > 50 ? 50 : entries; // cap at 5 ethereum
for (uint i = 0; i < entries; i++) {
memberQueue.push(msg.sender);
if (memberQueue.length % 2 == 1) {
queueFront += 1;
memberQueue[queueFront-1].transfer(194 finney);
}
}
Joined(msg.sender, entries, memberQueue.length * 2);
// send back any unused ethereum
uint remainder = msg.value - (entries * 100 finney);
if (remainder > 1 finney) {
msg.sender.transfer(remainder);
}
//msg.sender.send(msg.value - entries * 100 finney);
}
function collectFee() onlymaster {
master.transfer(this.balance - 200 finney);
}
function setMaster(address _master) onlymaster {
master = _master;
}
}
| send back any unused ethereum | uint remainder = msg.value - (entries * 100 finney);
| 12,851,452 | [
1,
4661,
1473,
1281,
10197,
13750,
822,
379,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
10022,
273,
1234,
18,
1132,
300,
261,
8219,
380,
2130,
574,
82,
402,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x14fbca95be7e99c15cc2996c6c9d841e54b79425
//Contract name: MatchingMarket
//Balance: 0 Ether
//Verification Date: 12/18/2017
//Transacion Count: 171303
// CODE STARTS HERE
pragma solidity ^0.4.18;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
contract EventfulMarket {
event LogItemUpdate(uint id);
event LogTrade(uint pay_amt, address indexed pay_gem,
uint buy_amt, address indexed buy_gem);
event LogMake(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
event LogBump(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
event LogTake(
bytes32 id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
address indexed taker,
uint128 take_amt,
uint128 give_amt,
uint64 timestamp
);
event LogKill(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
}
contract SimpleMarket is EventfulMarket, DSMath {
uint public last_offer_id;
mapping (uint => OfferInfo) public offers;
bool locked;
struct OfferInfo {
uint pay_amt;
ERC20 pay_gem;
uint buy_amt;
ERC20 buy_gem;
address owner;
uint64 timestamp;
}
modifier can_buy(uint id) {
require(isActive(id));
_;
}
modifier can_cancel(uint id) {
require(isActive(id));
require(getOwner(id) == msg.sender);
_;
}
modifier can_offer {
_;
}
modifier synchronized {
require(!locked);
locked = true;
_;
locked = false;
}
function isActive(uint id) public constant returns (bool active) {
return offers[id].timestamp > 0;
}
function getOwner(uint id) public constant returns (address owner) {
return offers[id].owner;
}
function getOffer(uint id) public constant returns (uint, ERC20, uint, ERC20) {
var offer = offers[id];
return (offer.pay_amt, offer.pay_gem,
offer.buy_amt, offer.buy_gem);
}
// ---- Public entrypoints ---- //
function bump(bytes32 id_)
public
can_buy(uint256(id_))
{
var id = uint256(id_);
LogBump(
id_,
keccak256(offers[id].pay_gem, offers[id].buy_gem),
offers[id].owner,
offers[id].pay_gem,
offers[id].buy_gem,
uint128(offers[id].pay_amt),
uint128(offers[id].buy_amt),
offers[id].timestamp
);
}
// Accept given `quantity` of an offer. Transfers funds from caller to
// offer maker, and from market to caller.
function buy(uint id, uint quantity)
public
can_buy(id)
synchronized
returns (bool)
{
OfferInfo memory offer = offers[id];
uint spend = mul(quantity, offer.buy_amt) / offer.pay_amt;
require(uint128(spend) == spend);
require(uint128(quantity) == quantity);
// For backwards semantic compatibility.
if (quantity == 0 || spend == 0 ||
quantity > offer.pay_amt || spend > offer.buy_amt)
{
return false;
}
offers[id].pay_amt = sub(offer.pay_amt, quantity);
offers[id].buy_amt = sub(offer.buy_amt, spend);
require( offer.buy_gem.transferFrom(msg.sender, offer.owner, spend) );
require( offer.pay_gem.transfer(msg.sender, quantity) );
LogItemUpdate(id);
LogTake(
bytes32(id),
keccak256(offer.pay_gem, offer.buy_gem),
offer.owner,
offer.pay_gem,
offer.buy_gem,
msg.sender,
uint128(quantity),
uint128(spend),
uint64(now)
);
LogTrade(quantity, offer.pay_gem, spend, offer.buy_gem);
if (offers[id].pay_amt == 0) {
delete offers[id];
}
return true;
}
// Cancel an offer. Refunds offer maker.
function cancel(uint id)
public
can_cancel(id)
synchronized
returns (bool success)
{
// read-only offer. Modify an offer by directly accessing offers[id]
OfferInfo memory offer = offers[id];
delete offers[id];
require( offer.pay_gem.transfer(offer.owner, offer.pay_amt) );
LogItemUpdate(id);
LogKill(
bytes32(id),
keccak256(offer.pay_gem, offer.buy_gem),
offer.owner,
offer.pay_gem,
offer.buy_gem,
uint128(offer.pay_amt),
uint128(offer.buy_amt),
uint64(now)
);
success = true;
}
function kill(bytes32 id)
public
{
require(cancel(uint256(id)));
}
function make(
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt
)
public
returns (bytes32 id)
{
return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem));
}
// Make a new offer. Takes funds from the caller into market escrow.
function offer(uint pay_amt, ERC20 pay_gem, uint buy_amt, ERC20 buy_gem)
public
can_offer
synchronized
returns (uint id)
{
require(uint128(pay_amt) == pay_amt);
require(uint128(buy_amt) == buy_amt);
require(pay_amt > 0);
require(pay_gem != ERC20(0x0));
require(buy_amt > 0);
require(buy_gem != ERC20(0x0));
require(pay_gem != buy_gem);
OfferInfo memory info;
info.pay_amt = pay_amt;
info.pay_gem = pay_gem;
info.buy_amt = buy_amt;
info.buy_gem = buy_gem;
info.owner = msg.sender;
info.timestamp = uint64(now);
id = _next_id();
offers[id] = info;
require( pay_gem.transferFrom(msg.sender, this, pay_amt) );
LogItemUpdate(id);
LogMake(
bytes32(id),
keccak256(pay_gem, buy_gem),
msg.sender,
pay_gem,
buy_gem,
uint128(pay_amt),
uint128(buy_amt),
uint64(now)
);
}
function take(bytes32 id, uint128 maxTakeAmount)
public
{
require(buy(uint256(id), maxTakeAmount));
}
function _next_id()
internal
returns (uint)
{
last_offer_id++; return last_offer_id;
}
}
// Simple Market with a market lifetime. When the close_time has been reached,
// offers can only be cancelled (offer and buy will throw).
contract ExpiringMarket is DSAuth, SimpleMarket {
uint64 public close_time;
bool public stopped;
// after close_time has been reached, no new offers are allowed
modifier can_offer {
require(!isClosed());
_;
}
// after close, no new buys are allowed
modifier can_buy(uint id) {
require(isActive(id));
require(!isClosed());
_;
}
// after close, anyone can cancel an offer
modifier can_cancel(uint id) {
require(isActive(id));
require(isClosed() || (msg.sender == getOwner(id)));
_;
}
function ExpiringMarket(uint64 _close_time)
public
{
close_time = _close_time;
}
function isClosed() public constant returns (bool closed) {
return stopped || getTime() > close_time;
}
function getTime() public constant returns (uint64) {
return uint64(now);
}
function stop() public auth {
stopped = true;
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract MatchingEvents {
event LogBuyEnabled(bool isEnabled);
event LogMinSell(address pay_gem, uint min_amount);
event LogMatchingEnabled(bool isEnabled);
event LogUnsortedOffer(uint id);
event LogSortedOffer(uint id);
event LogAddTokenPairWhitelist(ERC20 baseToken, ERC20 quoteToken);
event LogRemTokenPairWhitelist(ERC20 baseToken, ERC20 quoteToken);
event LogInsert(address keeper, uint id);
event LogDelete(address keeper, uint id);
}
contract MatchingMarket is MatchingEvents, ExpiringMarket, DSNote {
bool public buyEnabled = true; //buy enabled
bool public matchingEnabled = true; //true: enable matching,
//false: revert to expiring market
struct sortInfo {
uint next; //points to id of next higher offer
uint prev; //points to id of previous lower offer
uint delb; //the blocknumber where this entry was marked for delete
}
mapping(uint => sortInfo) public _rank; //doubly linked lists of sorted offer ids
mapping(address => mapping(address => uint)) public _best; //id of the highest offer for a token pair
mapping(address => mapping(address => uint)) public _span; //number of offers stored for token pair in sorted orderbook
mapping(address => uint) public _dust; //minimum sell amount for a token to avoid dust offers
mapping(uint => uint) public _near; //next unsorted offer id
mapping(bytes32 => bool) public _menu; //whitelist tracking which token pairs can be traded
uint _head; //first unsorted offer id
//check if token pair is enabled
modifier isWhitelist(ERC20 buy_gem, ERC20 pay_gem) {
require(_menu[keccak256(buy_gem, pay_gem)] || _menu[keccak256(pay_gem, buy_gem)]);
_;
}
function MatchingMarket(uint64 close_time) ExpiringMarket(close_time) public {
}
// ---- Public entrypoints ---- //
function make(
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt
)
public
returns (bytes32)
{
return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem));
}
function take(bytes32 id, uint128 maxTakeAmount) public {
require(buy(uint256(id), maxTakeAmount));
}
function kill(bytes32 id) public {
require(cancel(uint256(id)));
}
// Make a new offer. Takes funds from the caller into market escrow.
//
// If matching is enabled:
// * creates new offer without putting it in
// the sorted list.
// * available to authorized contracts only!
// * keepers should call insert(id,pos)
// to put offer in the sorted list.
//
// If matching is disabled:
// * calls expiring market's offer().
// * available to everyone without authorization.
// * no sorting is done.
//
function offer(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //taker (ask) buy how much
ERC20 buy_gem //taker (ask) buy which token
)
public
isWhitelist(pay_gem, buy_gem)
/* NOT synchronized!!! */
returns (uint)
{
var fn = matchingEnabled ? _offeru : super.offer;
return fn(pay_amt, pay_gem, buy_amt, buy_gem);
}
// Make a new offer. Takes funds from the caller into market escrow.
function offer(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //maker (ask) buy how much
ERC20 buy_gem, //maker (ask) buy which token
uint pos //position to insert offer, 0 should be used if unknown
)
public
isWhitelist(pay_gem, buy_gem)
/*NOT synchronized!!! */
can_offer
returns (uint)
{
return offer(pay_amt, pay_gem, buy_amt, buy_gem, pos, false);
}
function offer(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //maker (ask) buy how much
ERC20 buy_gem, //maker (ask) buy which token
uint pos, //position to insert offer, 0 should be used if unknown
bool rounding //match "close enough" orders?
)
public
isWhitelist(pay_gem, buy_gem)
/*NOT synchronized!!! */
can_offer
returns (uint)
{
require(_dust[pay_gem] <= pay_amt);
if (matchingEnabled) {
return _matcho(pay_amt, pay_gem, buy_amt, buy_gem, pos, rounding);
}
return super.offer(pay_amt, pay_gem, buy_amt, buy_gem);
}
//Transfers funds from caller to offer maker, and from market to caller.
function buy(uint id, uint amount)
public
/*NOT synchronized!!! */
can_buy(id)
returns (bool)
{
var fn = matchingEnabled ? _buys : super.buy;
return fn(id, amount);
}
// Cancel an offer. Refunds offer maker.
function cancel(uint id)
public
/*NOT synchronized!!! */
can_cancel(id)
returns (bool success)
{
if (matchingEnabled) {
if (isOfferSorted(id)) {
require(_unsort(id));
} else {
require(_hide(id));
}
}
return super.cancel(id); //delete the offer.
}
//insert offer into the sorted list
//keepers need to use this function
function insert(
uint id, //maker (ask) id
uint pos //position to insert into
)
public
returns (bool)
{
require(!isOfferSorted(id)); //make sure offers[id] is not yet sorted
require(isActive(id)); //make sure offers[id] is active
_hide(id); //remove offer from unsorted offers list
_sort(id, pos); //put offer into the sorted offers list
LogInsert(msg.sender, id);
return true;
}
//deletes _rank [id]
// Function should be called by keepers.
function del_rank(uint id)
public
returns (bool)
{
require(!isActive(id) && _rank[id].delb != 0 && _rank[id].delb < block.number - 10);
delete _rank[id];
LogDelete(msg.sender, id);
return true;
}
//returns true if token is succesfully added to whitelist
// Function is used to add a token pair to the whitelist
// All incoming offers are checked against the whitelist.
function addTokenPairWhitelist(
ERC20 baseToken,
ERC20 quoteToken
)
public
auth
note
returns (bool)
{
require(!isTokenPairWhitelisted(baseToken, quoteToken));
require(address(baseToken) != 0x0 && address(quoteToken) != 0x0);
_menu[keccak256(baseToken, quoteToken)] = true;
LogAddTokenPairWhitelist(baseToken, quoteToken);
return true;
}
//returns true if token is successfully removed from whitelist
// Function is used to remove a token pair from the whitelist.
// All incoming offers are checked against the whitelist.
function remTokenPairWhitelist(
ERC20 baseToken,
ERC20 quoteToken
)
public
auth
note
returns (bool)
{
require(isTokenPairWhitelisted(baseToken, quoteToken));
delete _menu[keccak256(baseToken, quoteToken)];
delete _menu[keccak256(quoteToken, baseToken)];
LogRemTokenPairWhitelist(baseToken, quoteToken);
return true;
}
function isTokenPairWhitelisted(
ERC20 baseToken,
ERC20 quoteToken
)
public
constant
returns (bool)
{
return (_menu[keccak256(baseToken, quoteToken)] || _menu[keccak256(quoteToken, baseToken)]);
}
//set the minimum sell amount for a token
// Function is used to avoid "dust offers" that have
// very small amount of tokens to sell, and it would
// cost more gas to accept the offer, than the value
// of tokens received.
function setMinSell(
ERC20 pay_gem, //token to assign minimum sell amount to
uint dust //maker (ask) minimum sell amount
)
public
auth
note
returns (bool)
{
_dust[pay_gem] = dust;
LogMinSell(pay_gem, dust);
return true;
}
//returns the minimum sell amount for an offer
function getMinSell(
ERC20 pay_gem //token for which minimum sell amount is queried
)
public
constant
returns (uint)
{
return _dust[pay_gem];
}
//set buy functionality enabled/disabled
function setBuyEnabled(bool buyEnabled_) public auth returns (bool) {
buyEnabled = buyEnabled_;
LogBuyEnabled(buyEnabled);
return true;
}
//set matching enabled/disabled
// If matchingEnabled true(default), then inserted offers are matched.
// Except the ones inserted by contracts, because those end up
// in the unsorted list of offers, that must be later sorted by
// keepers using insert().
// If matchingEnabled is false then MatchingMarket is reverted to ExpiringMarket,
// and matching is not done, and sorted lists are disabled.
function setMatchingEnabled(bool matchingEnabled_) public auth returns (bool) {
matchingEnabled = matchingEnabled_;
LogMatchingEnabled(matchingEnabled);
return true;
}
//return the best offer for a token pair
// the best offer is the lowest one if it's an ask,
// and highest one if it's a bid offer
function getBestOffer(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint) {
return _best[sell_gem][buy_gem];
}
//return the next worse offer in the sorted list
// the worse offer is the higher one if its an ask,
// a lower one if its a bid offer,
// and in both cases the newer one if they're equal.
function getWorseOffer(uint id) public constant returns(uint) {
return _rank[id].prev;
}
//return the next better offer in the sorted list
// the better offer is in the lower priced one if its an ask,
// the next higher priced one if its a bid offer
// and in both cases the older one if they're equal.
function getBetterOffer(uint id) public constant returns(uint) {
return _rank[id].next;
}
//return the amount of better offers for a token pair
function getOfferCount(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint) {
return _span[sell_gem][buy_gem];
}
//get the first unsorted offer that was inserted by a contract
// Contracts can't calculate the insertion position of their offer because it is not an O(1) operation.
// Their offers get put in the unsorted list of offers.
// Keepers can calculate the insertion position offchain and pass it to the insert() function to insert
// the unsorted offer into the sorted list. Unsorted offers will not be matched, but can be bought with buy().
function getFirstUnsortedOffer() public constant returns(uint) {
return _head;
}
//get the next unsorted offer
// Can be used to cycle through all the unsorted offers.
function getNextUnsortedOffer(uint id) public constant returns(uint) {
return _near[id];
}
function isOfferSorted(uint id) public constant returns(bool) {
return _rank[id].next != 0
|| _rank[id].prev != 0
|| _best[offers[id].pay_gem][offers[id].buy_gem] == id;
}
function sellAllAmount(ERC20 pay_gem, uint pay_amt, ERC20 buy_gem, uint min_fill_amount)
public
returns (uint fill_amt)
{
uint offerId;
while (pay_amt > 0) { //while there is amount to sell
offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair
require(offerId != 0); //Fails if there are not more offers
// There is a chance that pay_amt is smaller than 1 wei of the other token
if (pay_amt * 1 ether < wdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) {
break; //We consider that all amount is sold
}
if (pay_amt >= offers[offerId].buy_amt) { //If amount to sell is higher or equal than current offer amount to buy
fill_amt = add(fill_amt, offers[offerId].pay_amt); //Add amount bought to acumulator
pay_amt = sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to sell
take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer
} else { // if lower
var baux = rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9;
fill_amt = add(fill_amt, baux); //Add amount bought to acumulator
take(bytes32(offerId), uint128(baux)); //We take the portion of the offer that we need
pay_amt = 0; //All amount is sold
}
}
require(fill_amt >= min_fill_amount);
}
function buyAllAmount(ERC20 buy_gem, uint buy_amt, ERC20 pay_gem, uint max_fill_amount)
public
returns (uint fill_amt)
{
uint offerId;
while (buy_amt > 0) { //Meanwhile there is amount to buy
offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair
require(offerId != 0);
// There is a chance that buy_amt is smaller than 1 wei of the other token
if (buy_amt * 1 ether < wdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) {
break; //We consider that all amount is sold
}
if (buy_amt >= offers[offerId].pay_amt) { //If amount to buy is higher or equal than current offer amount to sell
fill_amt = add(fill_amt, offers[offerId].buy_amt); //Add amount sold to acumulator
buy_amt = sub(buy_amt, offers[offerId].pay_amt); //Decrease amount to buy
take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer
} else { //if lower
fill_amt = add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9); //Add amount sold to acumulator
take(bytes32(offerId), uint128(buy_amt)); //We take the portion of the offer that we need
buy_amt = 0; //All amount is bought
}
}
require(fill_amt <= max_fill_amount);
}
function getBuyAmount(ERC20 buy_gem, ERC20 pay_gem, uint pay_amt) public constant returns (uint fill_amt) {
var offerId = getBestOffer(buy_gem, pay_gem); //Get best offer for the token pair
while (pay_amt > offers[offerId].buy_amt) {
fill_amt = add(fill_amt, offers[offerId].pay_amt); //Add amount to buy accumulator
pay_amt = sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to pay
if (pay_amt > 0) { //If we still need more offers
offerId = getWorseOffer(offerId); //We look for the next best offer
require(offerId != 0); //Fails if there are not enough offers to complete
}
}
fill_amt = add(fill_amt, rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9); //Add proportional amount of last offer to buy accumulator
}
function getPayAmount(ERC20 pay_gem, ERC20 buy_gem, uint buy_amt) public constant returns (uint fill_amt) {
var offerId = getBestOffer(buy_gem, pay_gem); //Get best offer for the token pair
while (buy_amt > offers[offerId].pay_amt) {
fill_amt = add(fill_amt, offers[offerId].buy_amt); //Add amount to pay accumulator
buy_amt = sub(buy_amt, offers[offerId].pay_amt); //Decrease amount to buy
if (buy_amt > 0) { //If we still need more offers
offerId = getWorseOffer(offerId); //We look for the next best offer
require(offerId != 0); //Fails if there are not enough offers to complete
}
}
fill_amt = add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9); //Add proportional amount of last offer to pay accumulator
}
// ---- Internal Functions ---- //
function _buys(uint id, uint amount)
internal
returns (bool)
{
require(buyEnabled);
if (amount == offers[id].pay_amt && isOfferSorted(id)) {
//offers[id] must be removed from sorted list because all of it is bought
_unsort(id);
}
require(super.buy(id, amount));
return true;
}
//find the id of the next higher offer after offers[id]
function _find(uint id)
internal
view
returns (uint)
{
require( id > 0 );
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
uint top = _best[pay_gem][buy_gem];
uint old_top = 0;
// Find the larger-than-id order whose successor is less-than-id.
while (top != 0 && _isPricedLtOrEq(id, top)) {
old_top = top;
top = _rank[top].prev;
}
return old_top;
}
//find the id of the next higher offer after offers[id]
function _findpos(uint id, uint pos)
internal
view
returns (uint)
{
require(id > 0);
// Look for an active order.
while (pos != 0 && !isActive(pos)) {
pos = _rank[pos].prev;
}
if (pos == 0) {
//if we got to the end of list without a single active offer
return _find(id);
} else {
// if we did find a nearby active offer
// Walk the order book down from there...
if(_isPricedLtOrEq(id, pos)) {
uint old_pos;
// Guaranteed to run at least once because of
// the prior if statements.
while (pos != 0 && _isPricedLtOrEq(id, pos)) {
old_pos = pos;
pos = _rank[pos].prev;
}
return old_pos;
// ...or walk it up.
} else {
while (pos != 0 && !_isPricedLtOrEq(id, pos)) {
pos = _rank[pos].next;
}
return pos;
}
}
}
//return true if offers[low] priced less than or equal to offers[high]
function _isPricedLtOrEq(
uint low, //lower priced offer's id
uint high //higher priced offer's id
)
internal
view
returns (bool)
{
return mul(offers[low].buy_amt, offers[high].pay_amt)
>= mul(offers[high].buy_amt, offers[low].pay_amt);
}
//these variables are global only because of solidity local variable limit
//match offers with taker offer, and execute token transactions
function _matcho(
uint t_pay_amt, //taker sell how much
ERC20 t_pay_gem, //taker sell which token
uint t_buy_amt, //taker buy how much
ERC20 t_buy_gem, //taker buy which token
uint pos, //position id
bool rounding //match "close enough" orders?
)
internal
returns (uint id)
{
uint best_maker_id; //highest maker id
uint t_buy_amt_old; //taker buy how much saved
uint m_buy_amt; //maker offer wants to buy this much token
uint m_pay_amt; //maker offer wants to sell this much token
// there is at least one offer stored for token pair
while (_best[t_buy_gem][t_pay_gem] > 0) {
best_maker_id = _best[t_buy_gem][t_pay_gem];
m_buy_amt = offers[best_maker_id].buy_amt;
m_pay_amt = offers[best_maker_id].pay_amt;
// Ugly hack to work around rounding errors. Based on the idea that
// the furthest the amounts can stray from their "true" values is 1.
// Ergo the worst case has t_pay_amt and m_pay_amt at +1 away from
// their "correct" values and m_buy_amt and t_buy_amt at -1.
// Since (c - 1) * (d - 1) > (a + 1) * (b + 1) is equivalent to
// c * d > a * b + a + b + c + d, we write...
if (mul(m_buy_amt, t_buy_amt) > mul(t_pay_amt, m_pay_amt) +
(rounding ? m_buy_amt + t_buy_amt + t_pay_amt + m_pay_amt : 0))
{
break;
}
// ^ The `rounding` parameter is a compromise borne of a couple days
// of discussion.
buy(best_maker_id, min(m_pay_amt, t_buy_amt));
t_buy_amt_old = t_buy_amt;
t_buy_amt = sub(t_buy_amt, min(m_pay_amt, t_buy_amt));
t_pay_amt = mul(t_buy_amt, t_pay_amt) / t_buy_amt_old;
if (t_pay_amt == 0 || t_buy_amt == 0) {
break;
}
}
if (t_buy_amt > 0 && t_pay_amt > 0) {
//new offer should be created
id = super.offer(t_pay_amt, t_pay_gem, t_buy_amt, t_buy_gem);
//insert offer into the sorted list
_sort(id, pos);
}
}
// Make a new offer without putting it in the sorted list.
// Takes funds from the caller into market escrow.
// ****Available to authorized contracts only!**********
// Keepers should call insert(id,pos) to put offer in the sorted list.
function _offeru(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //maker (ask) buy how much
ERC20 buy_gem //maker (ask) buy which token
)
internal
/*NOT synchronized!!! */
returns (uint id)
{
require(_dust[pay_gem] <= pay_amt);
id = super.offer(pay_amt, pay_gem, buy_amt, buy_gem);
_near[id] = _head;
_head = id;
LogUnsortedOffer(id);
}
//put offer into the sorted list
function _sort(
uint id, //maker (ask) id
uint pos //position to insert into
)
internal
{
require(isActive(id));
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
uint prev_id; //maker (ask) id
if (pos == 0 || !isOfferSorted(pos)) {
pos = _find(id);
} else {
pos = _findpos(id, pos);
//if user has entered a `pos` that belongs to another currency pair
//we start from scratch
if(pos != 0 && (offers[pos].pay_gem != offers[id].pay_gem
|| offers[pos].buy_gem != offers[id].buy_gem))
{
pos = 0;
pos=_find(id);
}
}
//requirement below is satisfied by statements above
//require(pos == 0 || isOfferSorted(pos));
if (pos != 0) { //offers[id] is not the highest offer
//requirement below is satisfied by statements above
//require(_isPricedLtOrEq(id, pos));
prev_id = _rank[pos].prev;
_rank[pos].prev = id;
_rank[id].next = pos;
} else { //offers[id] is the highest offer
prev_id = _best[pay_gem][buy_gem];
_best[pay_gem][buy_gem] = id;
}
if (prev_id != 0) { //if lower offer does exist
//requirement below is satisfied by statements above
//require(!_isPricedLtOrEq(id, prev_id));
_rank[prev_id].next = id;
_rank[id].prev = prev_id;
}
_span[pay_gem][buy_gem]++;
LogSortedOffer(id);
}
// Remove offer from the sorted list (does not cancel offer)
function _unsort(
uint id //id of maker (ask) offer to remove from sorted list
)
internal
returns (bool)
{
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
require(_span[pay_gem][buy_gem] > 0);
require(_rank[id].delb == 0 && //assert id is in the sorted list
isOfferSorted(id));
if (id != _best[pay_gem][buy_gem]) { // offers[id] is not the highest offer
require(_rank[_rank[id].next].prev == id);
_rank[_rank[id].next].prev = _rank[id].prev;
} else { //offers[id] is the highest offer
_best[pay_gem][buy_gem] = _rank[id].prev;
}
if (_rank[id].prev != 0) { //offers[id] is not the lowest offer
require(_rank[_rank[id].prev].next == id);
_rank[_rank[id].prev].next = _rank[id].next;
}
_span[pay_gem][buy_gem]--;
_rank[id].delb = block.number; //mark _rank[id] for deletion
return true;
}
//Hide offer from the unsorted order book (does not cancel offer)
function _hide(
uint id //id of maker offer to remove from unsorted list
)
internal
returns (bool)
{
uint uid = _head; //id of an offer in unsorted offers list
uint pre = uid; //id of previous offer in unsorted offers list
require(!isOfferSorted(id)); //make sure offer id is not in sorted offers list
if (_head == id) { //check if offer is first offer in unsorted offers list
_head = _near[id]; //set head to new first unsorted offer
_near[id] = 0; //delete order from unsorted order list
return true;
}
while (uid > 0 && uid != id) { //find offer in unsorted order list
pre = uid;
uid = _near[uid];
}
if (uid != id) { //did not find offer id in unsorted offers list
return false;
}
_near[pre] = _near[id]; //set previous unsorted offer to point to offer after offer id
_near[id] = 0; //delete order from unsorted order list
return true;
}
}
| offers[id] is not the highest offer
| if (id != _best[pay_gem][buy_gem]) { | 2,494,799 | [
1,
3674,
414,
63,
350,
65,
353,
486,
326,
9742,
10067,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
350,
480,
389,
12729,
63,
10239,
67,
23465,
6362,
70,
9835,
67,
23465,
5717,
288,
9079,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
// WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that
// requires ABIEncoderV2. Exercise caution when calling that specific function.
pragma experimental ABIEncoderV2;
interface DharmaSmartWalletImplementationV1Interface {
event CALLSUCCESS383( //inject NONSTANDARD NAMING
bytes32 actionID,
bool rolledBack,
uint256 nonce,
address to,
bytes data,
bytes returnData
);
event CALLFAILURE442( //inject NONSTANDARD NAMING
bytes32 actionID,
uint256 nonce,
address to,
bytes data,
string revertReason
);
// ABIEncoderV2 uses an array of Calls for executing generic batch calls.
struct Call {
address to;
bytes data;
}
// ABIEncoderV2 uses an array of CallReturns for handling generic batch calls.
struct CallReturn {
bool ok;
bytes returnData;
}
function WITHDRAWETHER963( //inject NONSTANDARD NAMING
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function EXECUTEACTION770( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData);
function RECOVER845(address newUserSigningKey) external; //inject NONSTANDARD NAMING
function EXECUTEACTIONWITHATOMICBATCHCALLS418( //inject NONSTANDARD NAMING
Call[] calldata calls,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool[] memory ok, bytes[] memory returnData);
function GETNEXTGENERICACTIONID981( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETGENERICACTIONID781( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETNEXTGENERICATOMICBATCHACTIONID957( //inject NONSTANDARD NAMING
Call[] calldata calls,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETGENERICATOMICBATCHACTIONID98( //inject NONSTANDARD NAMING
Call[] calldata calls,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
}
interface DharmaSmartWalletImplementationV3Interface {
event CANCEL692(uint256 cancelledNonce); //inject NONSTANDARD NAMING
event ETHWITHDRAWAL175(uint256 amount, address recipient); //inject NONSTANDARD NAMING
}
interface DharmaSmartWalletImplementationV4Interface {
event ESCAPED27(); //inject NONSTANDARD NAMING
function SETESCAPEHATCH554( //inject NONSTANDARD NAMING
address account,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function REMOVEESCAPEHATCH653( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function PERMANENTLYDISABLEESCAPEHATCH796( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function ESCAPE232() external; //inject NONSTANDARD NAMING
}
interface DharmaSmartWalletImplementationV7Interface {
// Fires when a new user signing key is set on the smart wallet.
event NEWUSERSIGNINGKEY833(address userSigningKey); //inject NONSTANDARD NAMING
// Fires when an error occurs as part of an attempted action.
event EXTERNALERROR24(address indexed source, string revertReason); //inject NONSTANDARD NAMING
// The smart wallet recognizes DAI, USDC, ETH, and SAI as supported assets.
enum AssetType {
DAI,
USDC,
ETH,
SAI
}
// Actions, or protected methods (i.e. not deposits) each have an action type.
enum ActionType {
Cancel,
SetUserSigningKey,
Generic,
GenericAtomicBatch,
SAIWithdrawal,
USDCWithdrawal,
ETHWithdrawal,
SetEscapeHatch,
RemoveEscapeHatch,
DisableEscapeHatch,
DAIWithdrawal,
SignatureVerification,
TradeEthForDai,
DAIBorrow,
USDCBorrow
}
function INITIALIZE336(address userSigningKey) external; //inject NONSTANDARD NAMING
function REPAYANDDEPOSIT967() external; //inject NONSTANDARD NAMING
function WITHDRAWDAI449( //inject NONSTANDARD NAMING
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function WITHDRAWUSDC811( //inject NONSTANDARD NAMING
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function CANCEL991( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata signature
) external;
function SETUSERSIGNINGKEY240( //inject NONSTANDARD NAMING
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function MIGRATESAITODAI522() external; //inject NONSTANDARD NAMING
function MIGRATECSAITODDAI208() external; //inject NONSTANDARD NAMING
function MIGRATECDAITODDAI660() external; //inject NONSTANDARD NAMING
function MIGRATECUSDCTODUSDC400() external; //inject NONSTANDARD NAMING
function GETBALANCES53() external view returns ( //inject NONSTANDARD NAMING
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 dDaiUnderlyingDaiBalance,
uint256 dUsdcUnderlyingUsdcBalance,
uint256 dEtherUnderlyingEtherBalance // always returns zero
);
function GETUSERSIGNINGKEY63() external view returns (address userSigningKey); //inject NONSTANDARD NAMING
function GETNONCE95() external view returns (uint256 nonce); //inject NONSTANDARD NAMING
function GETNEXTCUSTOMACTIONID792( //inject NONSTANDARD NAMING
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETCUSTOMACTIONID90( //inject NONSTANDARD NAMING
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETVERSION901() external pure returns (uint256 version); //inject NONSTANDARD NAMING
}
interface DharmaSmartWalletImplementationV8Interface {
function TRADEETHFORDAIANDMINTDDAI339( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData);
function GETNEXTETHFORDAIACTIONID361( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETETHFORDAIACTIONID368( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
}
interface ERC20Interface {
function TRANSFER153(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE270(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF992(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE583( //inject NONSTANDARD NAMING
address owner, address spender
) external view returns (uint256);
}
interface ERC1271Interface {
function ISVALIDSIGNATURE229( //inject NONSTANDARD NAMING
bytes calldata data, bytes calldata signature
) external view returns (bytes4 magicValue);
}
interface CTokenInterface {
function REDEEM466(uint256 redeemAmount) external returns (uint256 err); //inject NONSTANDARD NAMING
function TRANSFER153(address recipient, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE270(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF992(address account) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function ALLOWANCE583(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface DTokenInterface {
// These external functions trigger accrual on the dToken and backing cToken.
function MINT76(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING
function REDEEM466(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING215(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING
// These external functions only trigger accrual on the dToken.
function MINTVIACTOKEN796(uint256 cTokensToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING
// View and pure functions do not trigger accrual on the dToken or the cToken.
function BALANCEOFUNDERLYING317(address account) external view returns (uint256 underlyingBalance); //inject NONSTANDARD NAMING
}
interface USDCV1Interface {
function ISBLACKLISTED453(address _account) external view returns (bool); //inject NONSTANDARD NAMING
function PAUSED117() external view returns (bool); //inject NONSTANDARD NAMING
}
interface DharmaKeyRegistryInterface {
function GETKEY781() external view returns (address key); //inject NONSTANDARD NAMING
}
interface DharmaEscapeHatchRegistryInterface {
function SETESCAPEHATCH554(address newEscapeHatch) external; //inject NONSTANDARD NAMING
function REMOVEESCAPEHATCH653() external; //inject NONSTANDARD NAMING
function PERMANENTLYDISABLEESCAPEHATCH796() external; //inject NONSTANDARD NAMING
function GETESCAPEHATCH697() external view returns ( //inject NONSTANDARD NAMING
bool exists, address escapeHatch
);
}
interface TradeHelperInterface {
function TRADEETHFORDAI848( //inject NONSTANDARD NAMING
uint256 daiExpected, address target, bytes calldata data
) external payable returns (uint256 daiReceived);
}
interface RevertReasonHelperInterface {
function REASON113(uint256 code) external pure returns (string memory); //inject NONSTANDARD NAMING
}
interface EtherizedInterface {
function TRIGGERETHERTRANSFER345( //inject NONSTANDARD NAMING
address payable target, uint256 value
) external returns (bool success);
}
interface ConfigurationRegistryInterface {
function GET761(bytes32 key) external view returns (bytes32 value); //inject NONSTANDARD NAMING
}
library Address {
function ISCONTRACT235(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
library ECDSA {
function RECOVER845( //inject NONSTANDARD NAMING
bytes32 hash, bytes memory signature
) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(hash, v, r, s);
}
function TOETHSIGNEDMESSAGEHASH603(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract Etherized is EtherizedInterface {
address private constant _etherizer294 = address( //inject NONSTANDARD NAMING
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
function TRIGGERETHERTRANSFER345( //inject NONSTANDARD NAMING
address payable target, uint256 amount
) external returns (bool success) {
require(msg.sender == _etherizer294, "Etherized: only callable by Etherizer");
(success, ) = target.call.value(amount)("");
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
}
contract DharmaSmartWalletImplementationV11Staging is
DharmaSmartWalletImplementationV1Interface,
DharmaSmartWalletImplementationV3Interface,
DharmaSmartWalletImplementationV4Interface,
DharmaSmartWalletImplementationV7Interface,
DharmaSmartWalletImplementationV8Interface,
ERC1271Interface,
Etherized {
using Address for address;
using ECDSA for bytes32;
// WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS!
// The user signing key associated with this account is in storage slot 0.
// It is the core differentiator when it comes to the account in question.
address private _userSigningKey;
// The nonce associated with this account is in storage slot 1. Every time a
// signature is submitted, it must have the appropriate nonce, and once it has
// been accepted the nonce will be incremented.
uint256 private _nonce;
// The self-call context flag is in storage slot 2. Some protected functions
// may only be called externally from calls originating from other methods on
// this contract, which enables appropriate exception handling on reverts.
// Any storage should only be set immediately preceding a self-call and should
// be cleared upon entering the protected function being called.
bytes4 internal _selfCallContext;
// END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE!
// The smart wallet version will be used when constructing valid signatures.
uint256 internal constant _dharma_smart_wallet_version295 = 1011; //inject NONSTANDARD NAMING
// DharmaKeyRegistryV2Staging holds a public key to verify meta-transactions.
DharmaKeyRegistryInterface internal constant _dharma_key_registry438 = ( //inject NONSTANDARD NAMING
DharmaKeyRegistryInterface(0x00000000006c7f32F0cD1eA4C1383558eb68802D)
);
// Account recovery uses a hard-coded staging version of the recovery manager.
address internal constant _account_recovery_manager816 = address( //inject NONSTANDARD NAMING
0x2a7E7718b755F9868E6B64DD18C6886707DD9c10
);
// Users can designate an "escape hatch" account with the ability to sweep all
// funds from their smart wallet by using the Dharma Escape Hatch Registry.
DharmaEscapeHatchRegistryInterface internal constant _escape_hatch_registry980 = ( //inject NONSTANDARD NAMING
DharmaEscapeHatchRegistryInterface(0x00000000005280B515004B998a944630B6C663f8)
);
// Interface with dDai, dUSDC, Dai, USDC, Sai, cSai, cDai, cUSDC, & migrator.
DTokenInterface internal constant _ddai406 = DTokenInterface( //inject NONSTANDARD NAMING
0x00000000001876eB1444c986fD502e618c587430 // mainnet
);
DTokenInterface internal constant _dusdc174 = DTokenInterface( //inject NONSTANDARD NAMING
0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet
);
ERC20Interface internal constant _dai860 = ERC20Interface( //inject NONSTANDARD NAMING
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
ERC20Interface internal constant _usdc146 = ERC20Interface( //inject NONSTANDARD NAMING
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
CTokenInterface internal constant _cdai443 = CTokenInterface( //inject NONSTANDARD NAMING
0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643 // mainnet
);
CTokenInterface internal constant _cusdc481 = CTokenInterface( //inject NONSTANDARD NAMING
0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet
);
// The "trade helper" facilitates Eth-to-Dai trades in an isolated context.
TradeHelperInterface internal constant _trade_helper427 = TradeHelperInterface( //inject NONSTANDARD NAMING
0x421816CDFe2073945173c0c35799ec21261fB399
);
// The "revert reason helper" contains a collection of revert reason strings.
RevertReasonHelperInterface internal constant _revert_reason_helper415 = ( //inject NONSTANDARD NAMING
RevertReasonHelperInterface(0x9C0ccB765D3f5035f8b5Dd30fE375d5F4997D8E4)
);
ConfigurationRegistryInterface internal constant _config_registry519 = ( //inject NONSTANDARD NAMING
ConfigurationRegistryInterface(0xC5C0ead7Df3CeFC45c8F4592E3a0f1500949E75D)
);
bytes32 internal constant _enable_usdc_minting_key536 = bytes32( //inject NONSTANDARD NAMING
0x596746115f08448433597980d42b4541c0197187d07ffad9c7f66a471c49dbba
); // keccak256("allowAvailableUSDCToBeUsedToMintCUSDC")
// Compound returns a value of 0 to indicate success, or lack of an error.
uint256 internal constant _compound_success452 = 0; //inject NONSTANDARD NAMING
// ERC-1271 must return this magic value when `isValidSignature` is called.
bytes4 internal constant _erc_1271_magic_value586 = bytes4(0x20c13b0b); //inject NONSTANDARD NAMING
// Minimum supported deposit & non-maximum withdrawal size is .001 underlying.
uint256 private constant _just_under_one_1000th_dai594 = 999999999999999; //inject NONSTANDARD NAMING
uint256 private constant _just_under_one_1000th_usdc382 = 999; //inject NONSTANDARD NAMING
// Specify the amount of gas to supply when making Ether transfers.
uint256 private constant _eth_transfer_gas33 = 4999; //inject NONSTANDARD NAMING
constructor() public {
assert(
_enable_usdc_minting_key536 == keccak256(
bytes("allowAvailableUSDCToBeUsedToMintCUSDC")
)
);
}
function () external payable {}
function INITIALIZE336(address userSigningKey) external { //inject NONSTANDARD NAMING
// Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address) { revert(0, 0) } }
// Set up the user's signing key and emit a corresponding event.
_SETUSERSIGNINGKEY543(userSigningKey);
// Approve the dDai contract to transfer Dai on behalf of this contract.
if (_SETFULLAPPROVAL629(AssetType.DAI)) {
// Get the current Dai balance on this contract.
uint256 daiBalance = _dai860.BALANCEOF992(address(this));
// Try to deposit the full Dai balance to Dharma Dai.
_DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance);
}
// Approve the dUSDC contract to transfer USDC on behalf of this contract.
if (_SETFULLAPPROVAL629(AssetType.USDC)) {
// Get the current USDC balance on this contract.
uint256 usdcBalance = _usdc146.BALANCEOF992(address(this));
// Try to deposit the full Dai balance to Dharma USDC.
_DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance);
}
}
function REPAYANDDEPOSIT967() external { //inject NONSTANDARD NAMING
// Get the current Dai balance on this contract.
uint256 daiBalance = _dai860.BALANCEOF992(address(this));
// If there is any Dai balance, check for adequate approval for dDai.
if (daiBalance > 0) {
uint256 daiAllowance = _dai860.ALLOWANCE583(address(this), address(_ddai406));
// If allowance is insufficient, try to set it before depositing.
if (daiAllowance < daiBalance) {
if (_SETFULLAPPROVAL629(AssetType.DAI)) {
// Deposit the full available Dai balance to Dharma Dai.
_DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance);
}
// Otherwise, just go ahead and try the Dai deposit.
} else {
// Deposit the full available Dai balance to Dharma Dai.
_DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance);
}
}
// Get the current USDC balance on this contract.
uint256 usdcBalance = _usdc146.BALANCEOF992(address(this));
// If there is any USDC balance, check for adequate approval for dUSDC.
if (usdcBalance > 0) {
uint256 usdcAllowance = _usdc146.ALLOWANCE583(address(this), address(_dusdc174));
// If allowance is insufficient, try to set it before depositing.
if (usdcAllowance < usdcBalance) {
if (_SETFULLAPPROVAL629(AssetType.USDC)) {
// Deposit the full available USDC balance to Dharma USDC.
_DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance);
}
// Otherwise, just go ahead and try the USDC deposit.
} else {
// Deposit the full available USDC balance to Dharma USDC.
_DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance);
}
}
}
function WITHDRAWDAI449( //inject NONSTANDARD NAMING
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.DAIWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 Dai has been supplied.
if (amount <= _just_under_one_1000th_dai594) {
revert(_REVERTREASON31(0));
}
// Ensure that a non-zero recipient has been supplied.
if (recipient == address(0)) {
revert(_REVERTREASON31(1));
}
// Set the self-call context in order to call _withdrawDaiAtomic.
_selfCallContext = this.WITHDRAWDAI449.selector;
// Make the atomic self-call - if redeemUnderlying fails on dDai, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (the Dai transfer) fails, it will revert
// and roll back the first part of the call as well as fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._WITHDRAWDAIATOMIC5.selector, amount, recipient
));
// If the atomic call failed, emit an event signifying a transfer failure.
if (!ok) {
emit EXTERNALERROR24(address(_dai860), _REVERTREASON31(2));
} else {
// Set ok to false if the call succeeded but the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
function _WITHDRAWDAIATOMIC5( //inject NONSTANDARD NAMING
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_ENFORCESELFCALLFROM836(this.WITHDRAWDAI449.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
if (maxWithdraw) {
// First attempt to redeem all dDai if there is a balance.
_WITHDRAWMAXFROMDHARMATOKEN348(AssetType.DAI);
// Then transfer all Dai to recipient if there is a balance.
require(_TRANSFERMAX629(_dai860, recipient, false));
success = true;
} else {
// Attempt to withdraw specified Dai from Dharma Dai before proceeding.
if (_WITHDRAWFROMDHARMATOKEN513(AssetType.DAI, amount)) {
// At this point Dai transfer should never fail - wrap it just in case.
require(_dai860.TRANSFER153(recipient, amount));
success = true;
}
}
}
function WITHDRAWUSDC811( //inject NONSTANDARD NAMING
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.USDCWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 USDC has been supplied.
if (amount <= _just_under_one_1000th_usdc382) {
revert(_REVERTREASON31(3));
}
// Ensure that a non-zero recipient has been supplied.
if (recipient == address(0)) {
revert(_REVERTREASON31(1));
}
// Set the self-call context in order to call _withdrawUSDCAtomic.
_selfCallContext = this.WITHDRAWUSDC811.selector;
// Make the atomic self-call - if redeemUnderlying fails on dUSDC, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (USDC transfer) fails, it will revert
// and roll back the first part of the call as well as fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._WITHDRAWUSDCATOMIC942.selector, amount, recipient
));
if (!ok) {
// Find out why USDC transfer reverted (doesn't give revert reasons).
_DIAGNOSEANDEMITUSDCSPECIFICERROR976(_usdc146.TRANSFER153.selector);
} else {
// Set ok to false if the call succeeded but the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
function _WITHDRAWUSDCATOMIC942( //inject NONSTANDARD NAMING
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_ENFORCESELFCALLFROM836(this.WITHDRAWUSDC811.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
if (maxWithdraw) {
// Attempt to redeem all dUSDC from Dharma USDC if there is a balance.
_WITHDRAWMAXFROMDHARMATOKEN348(AssetType.USDC);
// Then transfer all USDC to recipient if there is a balance.
require(_TRANSFERMAX629(_usdc146, recipient, false));
success = true;
} else {
// Attempt to withdraw specified USDC from Dharma USDC before proceeding.
if (_WITHDRAWFROMDHARMATOKEN513(AssetType.USDC, amount)) {
// Ensure that the USDC transfer does not fail.
require(_usdc146.TRANSFER153(recipient, amount));
success = true;
}
}
}
function WITHDRAWETHER963( //inject NONSTANDARD NAMING
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.ETHWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that a non-zero amount of Ether has been supplied.
if (amount == 0) {
revert(_REVERTREASON31(4));
}
// Ensure that a non-zero recipient has been supplied.
if (recipient == address(0)) {
revert(_REVERTREASON31(1));
}
// Attempt to transfer Ether to the recipient and emit an appropriate event.
ok = _TRANSFERETH212(recipient, amount);
}
function CANCEL991( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata signature
) external {
// Get the current nonce.
uint256 nonceToCancel = _nonce;
// Ensure the caller or the supplied signature is valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.Cancel,
abi.encode(),
minimumActionGas,
signature,
signature
);
// Emit an event to validate that the nonce is no longer valid.
emit CANCEL692(nonceToCancel);
}
function EXECUTEACTION770( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
// Ensure that the `to` address is a contract and is not this contract.
_ENSUREVALIDGENERICCALLTARGET978(to);
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.Generic,
abi.encode(to, data),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this action. However, the call
// itself may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Perform the action via low-level call and set return values using result.
(ok, returnData) = to.call(data);
// Emit a CallSuccess or CallFailure event based on the outcome of the call.
if (ok) {
// Note: while the call succeeded, the action may still have "failed"
// (for example, successful calls to Compound can still return an error).
emit CALLSUCCESS383(actionID, false, nonce, to, data, returnData);
} else {
// Note: while the call failed, the nonce will still be incremented, which
// will invalidate all supplied signatures.
emit CALLFAILURE442(actionID, nonce, to, data, _DECODEREVERTREASON288(returnData));
}
}
function SETUSERSIGNINGKEY240( //inject NONSTANDARD NAMING
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.SetUserSigningKey,
abi.encode(userSigningKey),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set new user signing key on smart wallet and emit a corresponding event.
_SETUSERSIGNINGKEY543(userSigningKey);
}
function SETESCAPEHATCH554( //inject NONSTANDARD NAMING
address account,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.SetEscapeHatch,
abi.encode(account),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an escape hatch account has been provided.
if (account == address(0)) {
revert(_REVERTREASON31(5));
}
// Set a new escape hatch for the smart wallet unless it has been disabled.
_escape_hatch_registry980.SETESCAPEHATCH554(account);
}
function REMOVEESCAPEHATCH653( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.RemoveEscapeHatch,
abi.encode(),
minimumActionGas,
userSignature,
dharmaSignature
);
// Remove the escape hatch for the smart wallet if one is currently set.
_escape_hatch_registry980.REMOVEESCAPEHATCH653();
}
function PERMANENTLYDISABLEESCAPEHATCH796( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.DisableEscapeHatch,
abi.encode(),
minimumActionGas,
userSignature,
dharmaSignature
);
// Permanently disable the escape hatch mechanism for this smart wallet.
_escape_hatch_registry980.PERMANENTLYDISABLEESCAPEHATCH796();
}
function TRADEETHFORDAIANDMINTDDAI339( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 Dai will be received.
if (minimumDaiReceived <= _just_under_one_1000th_dai594) {
revert(_REVERTREASON31(31));
}
// Set the self-call context in order to call _tradeEthForDaiAndMintDDaiAtomic.
_selfCallContext = this.TRADEETHFORDAIANDMINTDDAI339.selector;
// Make the atomic self-call - if the swap fails or the received dai is not
// greater than or equal to the requirement, it will revert and roll back the
// atomic call as well as fire an ExternalError. If dDai is not successfully
// minted, the swap will succeed but an ExternalError for dDai will be fired.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._TRADEETHFORDAIANDMINTDDAIATOMIC657.selector,
ethToSupply, minimumDaiReceived, target, data
));
// If the atomic call failed, emit an event signifying a trade failure.
if (!ok) {
emit EXTERNALERROR24(
address(_trade_helper427), _DECODEREVERTREASON288(returnData)
);
}
}
function _TRADEETHFORDAIANDMINTDDAIATOMIC657( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data
) external returns (bool ok, bytes memory returnData) {
// Ensure caller is this contract and self-call context is correctly set.
_ENFORCESELFCALLFROM836(this.TRADEETHFORDAIANDMINTDDAI339.selector);
// Do swap using supplied Ether amount, minimum Dai, target, and data.
uint256 daiReceived = _trade_helper427.TRADEETHFORDAI848.value(ethToSupply)(
minimumDaiReceived, target, data
);
// Ensure that sufficient Dai was returned as a result of the swap.
if (daiReceived < minimumDaiReceived) {
revert(_REVERTREASON31(32));
}
// Attempt to deposit the dai received and mint Dharma Dai.
_DEPOSITDHARMATOKEN821(AssetType.DAI, daiReceived);
}
function ESCAPE232() external { //inject NONSTANDARD NAMING
// Get the escape hatch account, if one exists, for this account.
(bool exists, address escapeHatch) = _escape_hatch_registry980.GETESCAPEHATCH697();
// Ensure that an escape hatch is currently set for this smart wallet.
if (!exists) {
revert(_REVERTREASON31(6));
}
// Ensure that the escape hatch account is the caller.
if (msg.sender != escapeHatch) {
revert(_REVERTREASON31(7));
}
// Attempt to redeem all dDai for Dai on Dharma Dai.
_WITHDRAWMAXFROMDHARMATOKEN348(AssetType.DAI);
// Attempt to redeem all dUSDC for USDC on Dharma USDC.
_WITHDRAWMAXFROMDHARMATOKEN348(AssetType.USDC);
// Attempt to transfer the total Dai balance to the caller.
_TRANSFERMAX629(_dai860, msg.sender, true);
// Attempt to transfer the total USDC balance to the caller.
_TRANSFERMAX629(_usdc146, msg.sender, true);
// Attempt to transfer any residual cDai to the caller.
_TRANSFERMAX629(ERC20Interface(address(_cdai443)), msg.sender, true);
// Attempt to transfer any residual cUSDC to the caller.
_TRANSFERMAX629(ERC20Interface(address(_cusdc481)), msg.sender, true);
// Attempt to transfer any residual dDai to the caller.
_TRANSFERMAX629(ERC20Interface(address(_ddai406)), msg.sender, true);
// Attempt to transfer any residual dUSDC to the caller.
_TRANSFERMAX629(ERC20Interface(address(_dusdc174)), msg.sender, true);
// Determine if there is Ether at this address that should be transferred.
uint256 balance = address(this).balance;
if (balance > 0) {
// Attempt to transfer any Ether to caller and emit an appropriate event.
_TRANSFERETH212(msg.sender, balance);
}
// Emit an `Escaped` event.
emit ESCAPED27();
}
function RECOVER845(address newUserSigningKey) external { //inject NONSTANDARD NAMING
// Only the Account Recovery Manager contract may call this function.
if (msg.sender != _account_recovery_manager816) {
revert(_REVERTREASON31(8));
}
// Increment nonce to prevent signature reuse should original key be reset.
_nonce++;
// Set up the user's new dharma key and emit a corresponding event.
_SETUSERSIGNINGKEY543(newUserSigningKey);
}
function MIGRATESAITODAI522() external { //inject NONSTANDARD NAMING
revert();
}
function MIGRATECSAITODDAI208() external { //inject NONSTANDARD NAMING
revert();
}
function MIGRATECDAITODDAI660() external { //inject NONSTANDARD NAMING
_MIGRATECTOKENTODTOKEN6(AssetType.DAI);
}
function MIGRATECUSDCTODUSDC400() external { //inject NONSTANDARD NAMING
_MIGRATECTOKENTODTOKEN6(AssetType.USDC);
}
function GETBALANCES53() external view returns ( //inject NONSTANDARD NAMING
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 dDaiUnderlyingDaiBalance,
uint256 dUsdcUnderlyingUsdcBalance,
uint256 dEtherUnderlyingEtherBalance // always returns 0
) {
daiBalance = _dai860.BALANCEOF992(address(this));
usdcBalance = _usdc146.BALANCEOF992(address(this));
etherBalance = address(this).balance;
dDaiUnderlyingDaiBalance = _ddai406.BALANCEOFUNDERLYING317(address(this));
dUsdcUnderlyingUsdcBalance = _dusdc174.BALANCEOFUNDERLYING317(address(this));
}
function GETUSERSIGNINGKEY63() external view returns (address userSigningKey) { //inject NONSTANDARD NAMING
userSigningKey = _userSigningKey;
}
function GETNONCE95() external view returns (uint256 nonce) { //inject NONSTANDARD NAMING
nonce = _nonce;
}
function GETNEXTCUSTOMACTIONID792( //inject NONSTANDARD NAMING
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
action,
_VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503(action, amount, recipient),
_nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETCUSTOMACTIONID90( //inject NONSTANDARD NAMING
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
action,
_VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503(action, amount, recipient),
nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETNEXTGENERICACTIONID981( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.Generic,
abi.encode(to, data),
_nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETGENERICACTIONID781( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.Generic,
abi.encode(to, data),
nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETNEXTETHFORDAIACTIONID361( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
_nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETETHFORDAIACTIONID368( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function ISVALIDSIGNATURE229( //inject NONSTANDARD NAMING
bytes calldata data, bytes calldata signatures
) external view returns (bytes4 magicValue) {
// Get message hash digest and any additional context from data argument.
bytes32 digest;
bytes memory context;
if (data.length == 32) {
digest = abi.decode(data, (bytes32));
} else {
if (data.length < 64) {
revert(_REVERTREASON31(30));
}
(digest, context) = abi.decode(data, (bytes32, bytes));
}
// Get Dharma signature & user signature from combined signatures argument.
if (signatures.length != 130) {
revert(_REVERTREASON31(11));
}
bytes memory signaturesInMemory = signatures;
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signaturesInMemory, 0x20))
s := mload(add(signaturesInMemory, 0x40))
v := byte(0, mload(add(signaturesInMemory, 0x60)))
}
bytes memory dharmaSignature = abi.encodePacked(r, s, v);
assembly {
r := mload(add(signaturesInMemory, 0x61))
s := mload(add(signaturesInMemory, 0x81))
v := byte(0, mload(add(signaturesInMemory, 0xa1)))
}
bytes memory userSignature = abi.encodePacked(r, s, v);
// Validate user signature with `SignatureVerification` as the action type.
if (
!_VALIDATEUSERSIGNATURE499(
digest,
ActionType.SignatureVerification,
context,
_userSigningKey,
userSignature
)
) {
revert(_REVERTREASON31(12));
}
// Recover Dharma signature against key returned from Dharma Key Registry.
if (_GETDHARMASIGNINGKEY429() != digest.RECOVER845(dharmaSignature)) {
revert(_REVERTREASON31(13));
}
// Return the ERC-1271 magic value to indicate success.
magicValue = _erc_1271_magic_value586;
}
function GETIMPLEMENTATION136() external view returns (address implementation) { //inject NONSTANDARD NAMING
(bool ok, bytes memory returnData) = address(
0x0000000000b45D6593312ac9fdE193F3D0633644
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
function GETVERSION901() external pure returns (uint256 version) { //inject NONSTANDARD NAMING
version = _dharma_smart_wallet_version295;
}
function EXECUTEACTIONWITHATOMICBATCHCALLS418( //inject NONSTANDARD NAMING
Call[] memory calls,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) public returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
_ENSUREVALIDGENERICCALLTARGET978(calls[i].to);
}
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.GenericAtomicBatch,
abi.encode(calls),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this contract. However, one of the
// calls may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _executeActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.EXECUTEACTIONWITHATOMICBATCHCALLS418.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool externalOk, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._EXECUTEACTIONWITHATOMICBATCHCALLSATOMIC905.selector, calls
)
);
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
Call memory currentCall = calls[i];
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
// Emit CallSuccess or CallFailure event based on the outcome of the call.
if (callResults[i].ok) {
// Note: while the call succeeded, the action may still have "failed".
emit CALLSUCCESS383(
actionID,
!externalOk, // If another call failed this will have been rolled back
nonce,
currentCall.to,
currentCall.data,
callResults[i].returnData
);
} else {
// Note: while the call failed, the nonce will still be incremented,
// which will invalidate all supplied signatures.
emit CALLFAILURE442(
actionID,
nonce,
currentCall.to,
currentCall.data,
_DECODEREVERTREASON288(callResults[i].returnData)
);
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
function _EXECUTEACTIONWITHATOMICBATCHCALLSATOMIC905( //inject NONSTANDARD NAMING
Call[] memory calls
) public returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_ENFORCESELFCALLFROM836(this.EXECUTEACTIONWITHATOMICBATCHCALLS418.selector);
bool rollBack = false;
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
rollBack = true;
break;
}
}
if (rollBack) {
// Wrap in length encoding and revert (provide data instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
}
function GETNEXTGENERICATOMICBATCHACTIONID957( //inject NONSTANDARD NAMING
Call[] memory calls,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.GenericAtomicBatch,
abi.encode(calls),
_nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETGENERICATOMICBATCHACTIONID98( //inject NONSTANDARD NAMING
Call[] memory calls,
uint256 nonce,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.GenericAtomicBatch,
abi.encode(calls),
nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function _SETUSERSIGNINGKEY543(address userSigningKey) internal { //inject NONSTANDARD NAMING
// Ensure that a user signing key is set on this smart wallet.
if (userSigningKey == address(0)) {
revert(_REVERTREASON31(14));
}
_userSigningKey = userSigningKey;
emit NEWUSERSIGNINGKEY833(userSigningKey);
}
function _SETFULLAPPROVAL629(AssetType asset) internal returns (bool ok) { //inject NONSTANDARD NAMING
// Get asset's underlying token address and corresponding dToken address.
address token;
address dToken;
if (asset == AssetType.DAI) {
token = address(_dai860);
dToken = address(_ddai406);
} else {
token = address(_usdc146);
dToken = address(_dusdc174);
}
// Approve dToken contract to transfer underlying on behalf of this wallet.
(ok, ) = address(token).call(abi.encodeWithSelector(
// Note: since both Tokens have the same interface, just use DAI's.
_dai860.APPROVE270.selector, dToken, uint256(-1)
));
// Emit a corresponding event if the approval failed.
if (!ok) {
if (asset == AssetType.DAI) {
emit EXTERNALERROR24(address(_dai860), _REVERTREASON31(17));
} else {
// Find out why USDC transfer reverted (it doesn't give revert reasons).
_DIAGNOSEANDEMITUSDCSPECIFICERROR976(_usdc146.APPROVE270.selector);
}
}
}
function _DEPOSITDHARMATOKEN821(AssetType asset, uint256 balance) internal { //inject NONSTANDARD NAMING
// Only perform a deposit if the balance is at least .001 Dai or USDC.
if (
asset == AssetType.DAI && balance > _just_under_one_1000th_dai594 ||
asset == AssetType.USDC && (
balance > _just_under_one_1000th_usdc382 &&
uint256(_config_registry519.GET761(_enable_usdc_minting_key536)) != 0
)
) {
// Get dToken address for the asset type.
address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174);
// Attempt to mint the balance on the dToken contract.
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
// Note: since both dTokens have the same interface, just use dDai's.
_ddai406.MINT76.selector, balance
));
// Log an external error if something went wrong with the attempt.
_CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622(
asset, _ddai406.MINT76.selector, ok, data
);
}
}
function _WITHDRAWFROMDHARMATOKEN513( //inject NONSTANDARD NAMING
AssetType asset, uint256 balance
) internal returns (bool success) {
// Get dToken address for the asset type. (No custom ETH withdrawal action.)
address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174);
// Attempt to redeem the underlying balance from the dToken contract.
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
// Note: function selector is the same for each dToken so just use dDai's.
_ddai406.REDEEMUNDERLYING215.selector, balance
));
// Log an external error if something went wrong with the attempt.
success = _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622(
asset, _ddai406.REDEEMUNDERLYING215.selector, ok, data
);
}
function _WITHDRAWMAXFROMDHARMATOKEN348(AssetType asset) internal { //inject NONSTANDARD NAMING
// Get dToken address for the asset type. (No custom ETH withdrawal action.)
address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174);
// Try to retrieve the current dToken balance for this account.
ERC20Interface dTokenBalance;
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
dTokenBalance.BALANCEOF992.selector, address(this)
));
uint256 redeemAmount = 0;
if (ok && data.length == 32) {
redeemAmount = abi.decode(data, (uint256));
} else {
// Something went wrong with the balance check - log an ExternalError.
_CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622(
asset, dTokenBalance.BALANCEOF992.selector, ok, data
);
}
// Only perform the call to redeem if there is a non-zero balance.
if (redeemAmount > 0) {
// Attempt to redeem the underlying balance from the dToken contract.
(ok, data) = dToken.call(abi.encodeWithSelector(
// Function selector is the same for all dTokens, so just use dDai's.
_ddai406.REDEEM466.selector, redeemAmount
));
// Log an external error if something went wrong with the attempt.
_CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622(
asset, _ddai406.REDEEM466.selector, ok, data
);
}
}
function _TRANSFERMAX629( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, bool suppressRevert
) internal returns (bool success) {
// Get the current balance on the smart wallet for the supplied ERC20 token.
uint256 balance = 0;
bool balanceCheckWorked = true;
if (!suppressRevert) {
balance = token.BALANCEOF992(address(this));
} else {
// Try to retrieve current token balance for this account with 1/2 gas.
(bool ok, bytes memory data) = address(token).call.gas(gasleft() / 2)(
abi.encodeWithSelector(token.BALANCEOF992.selector, address(this))
);
if (ok && data.length == 32) {
balance = abi.decode(data, (uint256));
} else {
// Something went wrong with the balance check.
balanceCheckWorked = false;
}
}
// Only perform the call to transfer if there is a non-zero balance.
if (balance > 0) {
if (!suppressRevert) {
// Perform the transfer and pass along the returned boolean (or revert).
success = token.TRANSFER153(recipient, balance);
} else {
// Attempt transfer with 1/2 gas, allow reverts, and return call status.
(success, ) = address(token).call.gas(gasleft() / 2)(
abi.encodeWithSelector(token.TRANSFER153.selector, recipient, balance)
);
}
} else {
// Skip the transfer and return true as long as the balance check worked.
success = balanceCheckWorked;
}
}
function _TRANSFERETH212( //inject NONSTANDARD NAMING
address payable recipient, uint256 amount
) internal returns (bool success) {
// Attempt to transfer any Ether to caller and emit an event if it fails.
(success, ) = recipient.call.gas(_eth_transfer_gas33).value(amount)("");
if (!success) {
emit EXTERNALERROR24(recipient, _REVERTREASON31(18));
} else {
emit ETHWITHDRAWAL175(amount, recipient);
}
}
function _VALIDATEACTIONANDINCREMENTNONCE883( //inject NONSTANDARD NAMING
ActionType action,
bytes memory arguments,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) internal returns (bytes32 actionID, uint256 actionNonce) {
// Ensure that the current gas exceeds the minimum required action gas.
// This prevents griefing attacks where an attacker can invalidate a
// signature without providing enough gas for the action to succeed. Also
// note that some gas will be spent before this check is reached - supplying
// ~30,000 additional gas should suffice when submitting transactions. To
// skip this requirement, supply zero for the minimumActionGas argument.
if (minimumActionGas != 0) {
if (gasleft() < minimumActionGas) {
revert(_REVERTREASON31(19));
}
}
// Get the current nonce for the action to be performed.
actionNonce = _nonce;
// Get the user signing key that will be used to verify their signature.
address userSigningKey = _userSigningKey;
// Get the Dharma signing key that will be used to verify their signature.
address dharmaSigningKey = _GETDHARMASIGNINGKEY429();
// Determine the actionID - this serves as the signature hash.
actionID = _GETACTIONID195(
action,
arguments,
actionNonce,
minimumActionGas,
userSigningKey,
dharmaSigningKey
);
// Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID.
bytes32 messageHash = actionID.TOETHSIGNEDMESSAGEHASH603();
// Actions other than Cancel require both signatures; Cancel only needs one.
if (action != ActionType.Cancel) {
// Validate user signing key signature unless it is `msg.sender`.
if (msg.sender != userSigningKey) {
if (
!_VALIDATEUSERSIGNATURE499(
messageHash, action, arguments, userSigningKey, userSignature
)
) {
revert(_REVERTREASON31(20));
}
}
// Validate Dharma signing key signature unless it is `msg.sender`.
if (msg.sender != dharmaSigningKey) {
if (dharmaSigningKey != messageHash.RECOVER845(dharmaSignature)) {
revert(_REVERTREASON31(21));
}
}
} else {
// Validate signing key signature unless user or Dharma is `msg.sender`.
if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) {
if (
dharmaSigningKey != messageHash.RECOVER845(dharmaSignature) &&
!_VALIDATEUSERSIGNATURE499(
messageHash, action, arguments, userSigningKey, userSignature
)
) {
revert(_REVERTREASON31(22));
}
}
}
// Increment nonce in order to prevent reuse of signatures after the call.
_nonce++;
}
function _MIGRATECTOKENTODTOKEN6(AssetType token) internal { //inject NONSTANDARD NAMING
CTokenInterface cToken;
DTokenInterface dToken;
if (token == AssetType.DAI) {
cToken = _cdai443;
dToken = _ddai406;
} else {
cToken = _cusdc481;
dToken = _dusdc174;
}
// Get the current cToken balance for this account.
uint256 balance = cToken.BALANCEOF992(address(this));
// Only perform the conversion if there is a non-zero balance.
if (balance > 0) {
// If the allowance is insufficient, set it before depositing.
if (cToken.ALLOWANCE583(address(this), address(dToken)) < balance) {
if (!cToken.APPROVE270(address(dToken), uint256(-1))) {
revert(_REVERTREASON31(23));
}
}
// Deposit the new balance on the Dharma Token.
if (dToken.MINTVIACTOKEN796(balance) == 0) {
revert(_REVERTREASON31(24));
}
}
}
function _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622( //inject NONSTANDARD NAMING
AssetType asset,
bytes4 functionSelector,
bool ok,
bytes memory data
) internal returns (bool success) {
// Log an external error if something went wrong with the attempt.
if (ok) {
if (data.length == 32) {
uint256 amount = abi.decode(data, (uint256));
if (amount > 0) {
success = true;
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_GETDHARMATOKENDETAILS978(asset, functionSelector)
);
emit EXTERNALERROR24(
account,
string(
abi.encodePacked(
name,
" gave no tokens calling ",
functionName,
"."
)
)
);
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_GETDHARMATOKENDETAILS978(asset, functionSelector)
);
emit EXTERNALERROR24(
account,
string(
abi.encodePacked(
name,
" gave bad data calling ",
functionName,
"."
)
)
);
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_GETDHARMATOKENDETAILS978(asset, functionSelector)
);
// Decode the revert reason in the event one was returned.
string memory revertReason = _DECODEREVERTREASON288(data);
emit EXTERNALERROR24(
account,
string(
abi.encodePacked(
name,
" reverted calling ",
functionName,
": ",
revertReason
)
)
);
}
}
function _DIAGNOSEANDEMITUSDCSPECIFICERROR976(bytes4 functionSelector) internal { //inject NONSTANDARD NAMING
// Determine the name of the function that was called on USDC.
string memory functionName;
if (functionSelector == _usdc146.TRANSFER153.selector) {
functionName = "transfer";
} else {
functionName = "approve";
}
USDCV1Interface usdcNaughty = USDCV1Interface(address(_usdc146));
// Find out why USDC transfer reverted (it doesn't give revert reasons).
if (usdcNaughty.ISBLACKLISTED453(address(this))) {
emit EXTERNALERROR24(
address(_usdc146),
string(
abi.encodePacked(
functionName, " failed - USDC has blacklisted this user."
)
)
);
} else { // Note: `else if` breaks coverage.
if (usdcNaughty.PAUSED117()) {
emit EXTERNALERROR24(
address(_usdc146),
string(
abi.encodePacked(
functionName, " failed - USDC contract is currently paused."
)
)
);
} else {
emit EXTERNALERROR24(
address(_usdc146),
string(
abi.encodePacked(
"USDC contract reverted on ", functionName, "."
)
)
);
}
}
}
function _ENFORCESELFCALLFROM836(bytes4 selfCallContext) internal { //inject NONSTANDARD NAMING
// Ensure caller is this contract and self-call context is correctly set.
if (msg.sender != address(this) || _selfCallContext != selfCallContext) {
revert(_REVERTREASON31(25));
}
// Clear the self-call context.
delete _selfCallContext;
}
function _VALIDATEUSERSIGNATURE499( //inject NONSTANDARD NAMING
bytes32 messageHash,
ActionType action,
bytes memory arguments,
address userSigningKey,
bytes memory userSignature
) internal view returns (bool valid) {
if (!userSigningKey.ISCONTRACT235()) {
valid = userSigningKey == messageHash.RECOVER845(userSignature);
} else {
bytes memory data = abi.encode(messageHash, action, arguments);
valid = (
ERC1271Interface(userSigningKey).ISVALIDSIGNATURE229(
data, userSignature
) == _erc_1271_magic_value586
);
}
}
function _GETDHARMASIGNINGKEY429() internal view returns ( //inject NONSTANDARD NAMING
address dharmaSigningKey
) {
dharmaSigningKey = _dharma_key_registry438.GETKEY781();
}
function _GETACTIONID195( //inject NONSTANDARD NAMING
ActionType action,
bytes memory arguments,
uint256 nonce,
uint256 minimumActionGas,
address userSigningKey,
address dharmaSigningKey
) internal view returns (bytes32 actionID) {
// actionID is constructed according to EIP-191-0x45 to prevent replays.
actionID = keccak256(
abi.encodePacked(
address(this),
_dharma_smart_wallet_version295,
userSigningKey,
dharmaSigningKey,
nonce,
minimumActionGas,
action,
arguments
)
);
}
function _GETDHARMATOKENDETAILS978( //inject NONSTANDARD NAMING
AssetType asset,
bytes4 functionSelector
) internal pure returns (
address account,
string memory name,
string memory functionName
) {
if (asset == AssetType.DAI) {
account = address(_ddai406);
name = "Dharma Dai";
} else {
account = address(_dusdc174);
name = "Dharma USD Coin";
}
// Note: since both dTokens have the same interface, just use dDai's.
if (functionSelector == _ddai406.MINT76.selector) {
functionName = "mint";
} else {
if (functionSelector == ERC20Interface(account).BALANCEOF992.selector) {
functionName = "balanceOf";
} else {
functionName = string(abi.encodePacked(
"redeem",
functionSelector == _ddai406.REDEEM466.selector ? "" : "Underlying"
));
}
}
}
function _ENSUREVALIDGENERICCALLTARGET978(address to) internal view { //inject NONSTANDARD NAMING
if (!to.ISCONTRACT235()) {
revert(_REVERTREASON31(26));
}
if (to == address(this)) {
revert(_REVERTREASON31(27));
}
if (to == address(_escape_hatch_registry980)) {
revert(_REVERTREASON31(28));
}
}
function _VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503( //inject NONSTANDARD NAMING
ActionType action, uint256 amount, address recipient
) internal pure returns (bytes memory arguments) {
// Ensure that the action type is a valid custom action type.
bool validActionType = (
action == ActionType.Cancel ||
action == ActionType.SetUserSigningKey ||
action == ActionType.DAIWithdrawal ||
action == ActionType.USDCWithdrawal ||
action == ActionType.ETHWithdrawal ||
action == ActionType.SetEscapeHatch ||
action == ActionType.RemoveEscapeHatch ||
action == ActionType.DisableEscapeHatch
);
if (!validActionType) {
revert(_REVERTREASON31(29));
}
// Use action type to determine parameters to include in returned arguments.
if (
action == ActionType.Cancel ||
action == ActionType.RemoveEscapeHatch ||
action == ActionType.DisableEscapeHatch
) {
// Ignore parameters for Cancel, RemoveEscapeHatch, or DisableEscapeHatch.
arguments = abi.encode();
} else if (
action == ActionType.SetUserSigningKey ||
action == ActionType.SetEscapeHatch
) {
// Ignore `amount` parameter for other, non-withdrawal actions.
arguments = abi.encode(recipient);
} else {
// Use both `amount` and `recipient` parameters for withdrawals.
arguments = abi.encode(amount, recipient);
}
}
function _DECODEREVERTREASON288( //inject NONSTANDARD NAMING
bytes memory revertData
) internal pure returns (string memory revertReason) {
// Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector
if (
revertData.length > 68 && // prefix (4) + position (32) + length (32)
revertData[0] == byte(0x08) &&
revertData[1] == byte(0xc3) &&
revertData[2] == byte(0x79) &&
revertData[3] == byte(0xa0)
) {
// Get the revert reason without the prefix from the revert data.
bytes memory revertReasonBytes = new bytes(revertData.length - 4);
for (uint256 i = 4; i < revertData.length; i++) {
revertReasonBytes[i - 4] = revertData[i];
}
// Decode the resultant revert reason as a string.
revertReason = abi.decode(revertReasonBytes, (string));
} else {
// Simply return the default, with no revert reason.
revertReason = _REVERTREASON31(uint256(-1));
}
}
function _REVERTREASON31( //inject NONSTANDARD NAMING
uint256 code
) internal pure returns (string memory reason) {
reason = _revert_reason_helper415.REASON113(code);
}
} | Ensure caller and/or supplied signatures are valid and increment nonce. Ensure that an amount of at least 0.001 Dai will be received. | ) external returns (bool ok, bytes memory returnData) {
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
minimumActionGas,
userSignature,
dharmaSignature
);
if (minimumDaiReceived <= _just_under_one_1000th_dai594) {
revert(_REVERTREASON31(31));
}
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._TRADEETHFORDAIANDMINTDDAIATOMIC657.selector,
ethToSupply, minimumDaiReceived, target, data
));
_selfCallContext = this.TRADEETHFORDAIANDMINTDDAI339.selector;
bytes memory returnData;
if (!ok) {
emit EXTERNALERROR24(
address(_trade_helper427), _DECODEREVERTREASON288(returnData)
);
}
}
| 5,492,107 | [
1,
12512,
4894,
471,
19,
280,
4580,
14862,
854,
923,
471,
5504,
7448,
18,
7693,
716,
392,
3844,
434,
622,
4520,
374,
18,
11664,
463,
10658,
903,
506,
5079,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
262,
3903,
1135,
261,
6430,
1529,
16,
1731,
3778,
327,
751,
13,
288,
203,
565,
389,
14687,
12249,
4307,
29836,
3993,
1441,
5482,
23,
12,
203,
1377,
4382,
559,
18,
22583,
41,
451,
1290,
40,
10658,
16,
203,
1377,
24126,
18,
3015,
12,
546,
774,
3088,
1283,
16,
5224,
40,
10658,
8872,
16,
1018,
16,
501,
3631,
203,
1377,
5224,
1803,
27998,
16,
203,
1377,
729,
5374,
16,
203,
1377,
11007,
297,
2540,
5374,
203,
565,
11272,
203,
203,
565,
309,
261,
15903,
40,
10658,
8872,
1648,
389,
3732,
67,
9341,
67,
476,
67,
18088,
451,
67,
2414,
77,
6162,
24,
13,
288,
203,
1377,
15226,
24899,
862,
21654,
29416,
1413,
6938,
12,
6938,
10019,
203,
565,
289,
203,
203,
203,
565,
261,
601,
16,
327,
751,
13,
273,
1758,
12,
2211,
2934,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
203,
1377,
333,
6315,
20060,
1639,
1584,
44,
7473,
9793,
45,
4307,
49,
3217,
5698,
18194,
28146,
2871,
9222,
27,
18,
9663,
16,
203,
1377,
13750,
774,
3088,
1283,
16,
5224,
40,
10658,
8872,
16,
1018,
16,
501,
203,
565,
262,
1769,
203,
203,
565,
389,
2890,
22582,
273,
333,
18,
20060,
1639,
1584,
44,
7473,
9793,
45,
4307,
49,
3217,
5698,
18194,
3707,
29,
18,
9663,
31,
203,
565,
1731,
3778,
327,
751,
31,
203,
565,
309,
16051,
601,
13,
288,
203,
1377,
3626,
5675,
11702,
3589,
3247,
12,
203,
3639,
1758,
24899,
20077,
67,
4759,
24,
5324,
3631,
389,
1639,
9086,
29340,
21654,
29416,
1413,
22,
5482,
12,
2463,
751,
2
] |
./partial_match/1/0x0C2455CbA836c832144Ff58ECBfC366C69E69ca0/sources/TheBigMouse.sol | * PAY Mint 0.001 FOR EACH ONE/ | function mint(uint256 amount) payable public {
require(totalSupply() + 1 <= _maxSupply, "Sold Out");
require(amount <= _maxPerTx);
uint256 cost = amount * _price;
require(msg.value >= cost, "Pay For");
_safeMint(msg.sender, amount);
}
| 2,882,753 | [
1,
11389,
490,
474,
374,
18,
11664,
12108,
512,
18133,
15623,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
11890,
5034,
3844,
13,
8843,
429,
1071,
288,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
397,
404,
1648,
389,
1896,
3088,
1283,
16,
315,
55,
1673,
2976,
8863,
203,
3639,
2583,
12,
8949,
1648,
389,
1896,
2173,
4188,
1769,
203,
3639,
2254,
5034,
6991,
273,
3844,
380,
389,
8694,
31,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
6991,
16,
315,
9148,
2457,
8863,
203,
3639,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x862852527c322b2bBd7aA4eBE4ba31f398A92DE6/sources/TradfiFinance.sol | * @dev Sets the value of the `decimals`. This value is immutable, it can only be set once during construction./ | constructor () ERC20('Tradfi.Finance', 'TradFi') {
_mint(_msgSender(), _totalSupply);
}
| 4,497,282 | [
1,
2785,
326,
460,
434,
326,
1375,
31734,
8338,
1220,
460,
353,
11732,
16,
518,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1832,
4232,
39,
3462,
2668,
1609,
2180,
77,
18,
6187,
1359,
2187,
296,
1609,
72,
42,
77,
6134,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x9cDeFe6Bfae3afb3D88BB9c4e414fE99d5B76539/sources/project_/contracts/Tickets.sol | 價格若為 0,代表這張票已經被賣出 賣家 | struct Ticket {
uint256 price;
address owner;
}
| 1,863,471 | [
1,
166,
230,
122,
167,
259,
125,
169,
238,
103,
168,
229,
123,
374,
176,
125,
239,
165,
124,
101,
169,
99,
106,
170,
227,
252,
166,
125,
118,
168,
103,
106,
166,
120,
115,
168,
119,
246,
169,
100,
109,
169,
116,
101,
166,
234,
123,
225,
169,
116,
101,
166,
111,
119,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
22023,
288,
203,
3639,
2254,
5034,
6205,
31,
203,
3639,
1758,
3410,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.21;
pragma experimental "v0.5.0";
interface Token {
function totalSupply() external returns (uint256);
function balanceOf(address) external returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
function approve(address, uint256) external returns (bool);
function allowance(address, address) external returns (uint256);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Dex2 {
//------------------------------ Struct Definitions: ---------------------------------------------
struct TokenInfo {
string symbol; // e.g., "ETH", "ADX"
address tokenAddr; // ERC20 token address
uint64 scaleFactor; // <original token amount> = <scaleFactor> x <DEx amountE8> / 1e8
uint minDeposit; // mininum deposit (original token amount) allowed for this token
}
struct TraderInfo {
address withdrawAddr;
uint8 feeRebatePercent; // range: [0, 100]
}
struct TokenAccount {
uint64 balanceE8; // available amount for trading
uint64 pendingWithdrawE8; // the amount to be transferred out from this contract to the trader
}
struct Order {
uint32 pairId; // <cashId>(16) <stockId>(16)
uint8 action; // 0 means BUY; 1 means SELL
uint8 ioc; // 0 means a regular order; 1 means an immediate-or-cancel (IOC) order
uint64 priceE8;
uint64 amountE8;
uint64 expireTimeSec;
}
struct Deposit {
address traderAddr;
uint16 tokenCode;
uint64 pendingAmountE8; // amount to be confirmed for trading purpose
}
struct DealInfo {
uint16 stockCode; // stock token code
uint16 cashCode; // cash token code
uint64 stockDealAmountE8;
uint64 cashDealAmountE8;
}
struct ExeStatus {
uint64 logicTimeSec; // logic timestamp for checking order expiration
uint64 lastOperationIndex; // index of the last executed operation
}
//----------------- Constants: -------------------------------------------------------------------
uint constant MAX_UINT256 = 2**256 - 1;
uint16 constant MAX_FEE_RATE_E4 = 60; // the upper limit of a fee rate is 0.6%
// <original ETH amount in Wei> = <DEx amountE8> * <ETH_SCALE_FACTOR> / 1e8
uint64 constant ETH_SCALE_FACTOR = 10**18;
uint8 constant ACTIVE = 0;
uint8 constant CLOSED = 2;
bytes32 constant HASHTYPES =
keccak256('string title', 'address market_address', 'uint64 nonce', 'uint64 expire_time_sec',
'uint64 amount_e8', 'uint64 price_e8', 'uint8 immediate_or_cancel', 'uint8 action',
'uint16 cash_token_code', 'uint16 stock_token_code');
//----------------- States that cannot be changed once set: --------------------------------------
address public admin; // admin address, and it cannot be changed
mapping (uint16 => TokenInfo) public tokens; // mapping of token code to token information
//----------------- Other states: ----------------------------------------------------------------
uint8 public marketStatus; // market status: 0 - Active; 1 - Suspended; 2 - Closed
uint16 public makerFeeRateE4; // maker fee rate (* 10**4)
uint16 public takerFeeRateE4; // taker fee rate (* 10**4)
uint16 public withdrawFeeRateE4; // withdraw fee rate (* 10**4)
uint64 public lastDepositIndex; // index of the last deposit operation
ExeStatus public exeStatus; // status of operation execution
mapping (address => TraderInfo) public traders; // mapping of trade address to trader information
mapping (uint176 => TokenAccount) public accounts; // mapping of trader token key to its account information
mapping (uint224 => Order) public orders; // mapping of order key to order information
mapping (uint64 => Deposit) public deposits; // mapping of deposit index to deposit information
//------------------------------ Dex2 Events: ----------------------------------------------------
event DeployMarketEvent();
event ChangeMarketStatusEvent(uint8 status);
event SetTokenInfoEvent(uint16 tokenCode, string symbol, address tokenAddr, uint64 scaleFactor, uint minDeposit);
event SetWithdrawAddrEvent(address trader, address withdrawAddr);
event DepositEvent(address trader, uint16 tokenCode, string symbol, uint64 amountE8, uint64 depositIndex);
event WithdrawEvent(address trader, uint16 tokenCode, string symbol, uint64 amountE8, uint64 lastOpIndex);
event TransferFeeEvent(uint16 tokenCode, uint64 amountE8, address toAddr);
// `balanceE8` is the total balance after this deposit confirmation
event ConfirmDepositEvent(address trader, uint16 tokenCode, uint64 balanceE8);
// `amountE8` is the post-fee initiated withdraw amount
// `pendingWithdrawE8` is the total pending withdraw amount after this withdraw initiation
event InitiateWithdrawEvent(address trader, uint16 tokenCode, uint64 amountE8, uint64 pendingWithdrawE8);
event MatchOrdersEvent(address trader1, uint64 nonce1, address trader2, uint64 nonce2);
event HardCancelOrderEvent(address trader, uint64 nonce);
event SetFeeRatesEvent(uint16 makerFeeRateE4, uint16 takerFeeRateE4, uint16 withdrawFeeRateE4);
event SetFeeRebatePercentEvent(address trader, uint8 feeRebatePercent);
//------------------------------ Contract Initialization: ----------------------------------------
function Dex2(address admin_) public {
admin = admin_;
setTokenInfo(0 /*tokenCode*/, "ETH", 0 /*tokenAddr*/, ETH_SCALE_FACTOR, 0 /*minDeposit*/);
emit DeployMarketEvent();
}
//------------------------------ External Functions: ---------------------------------------------
function() external {
revert();
}
// Change the market status of DEX.
function changeMarketStatus(uint8 status_) external {
if (msg.sender != admin) revert();
if (marketStatus == CLOSED) revert(); // closed is forever
marketStatus = status_;
emit ChangeMarketStatusEvent(status_);
}
function setWithdrawAddr(address withdrawAddr) external {
if (withdrawAddr == 0) revert();
if (traders[msg.sender].withdrawAddr != 0) revert(); // cannot change withdrawAddr once set
traders[msg.sender].withdrawAddr = withdrawAddr;
emit SetWithdrawAddrEvent(msg.sender, withdrawAddr);
}
// Deposits ETH from msg.sender for the given trader.
function depositEth(address traderAddr) external payable {
if (marketStatus != ACTIVE) revert();
if (traderAddr == 0) revert();
if (msg.value < tokens[0].minDeposit) revert();
if (msg.data.length != 4 + 32) revert(); // length condition of param count
uint64 pendingAmountE8 = uint64(msg.value / (ETH_SCALE_FACTOR / 10**8)); // msg.value is in Wei
if (pendingAmountE8 == 0) revert();
uint64 depositIndex = ++lastDepositIndex;
setDeposits(depositIndex, traderAddr, 0, pendingAmountE8);
emit DepositEvent(traderAddr, 0, "ETH", pendingAmountE8, depositIndex);
}
// Deposits token (other than ETH) from msg.sender for a specified trader.
//
// After this deposit has been confirmed enough times on the blockchain, it will be added to
// the trader's token account for trading.
function depositToken(address traderAddr, uint16 tokenCode, uint originalAmount) external {
if (marketStatus != ACTIVE) revert();
if (traderAddr == 0) revert();
if (tokenCode == 0) revert(); // this function does not handle ETH
if (msg.data.length != 4 + 32 + 32 + 32) revert(); // length condition of param count
TokenInfo memory tokenInfo = tokens[tokenCode];
if (originalAmount < tokenInfo.minDeposit) revert();
if (tokenInfo.scaleFactor == 0) revert(); // unsupported token
// Remember to call Token(address).approve(this, amount) from msg.sender in advance.
if (!Token(tokenInfo.tokenAddr).transferFrom(msg.sender, this, originalAmount)) revert();
if (originalAmount > MAX_UINT256 / 10**8) revert(); // avoid overflow
uint amountE8 = originalAmount * 10**8 / uint(tokenInfo.scaleFactor);
if (amountE8 >= 2**64 || amountE8 == 0) revert();
uint64 depositIndex = ++lastDepositIndex;
setDeposits(depositIndex, traderAddr, tokenCode, uint64(amountE8));
emit DepositEvent(traderAddr, tokenCode, tokens[tokenCode].symbol, uint64(amountE8), depositIndex);
}
// Withdraw ETH from the contract.
function withdrawEth(address traderAddr) external {
if (traderAddr == 0) revert();
if (msg.data.length != 4 + 32) revert(); // length condition of param count
uint176 accountKey = uint176(traderAddr);
uint amountE8 = accounts[accountKey].pendingWithdrawE8;
if (amountE8 == 0) return;
// Write back to storage before making the transfer.
accounts[accountKey].pendingWithdrawE8 = 0;
uint truncatedWei = amountE8 * (ETH_SCALE_FACTOR / 10**8);
address withdrawAddr = traders[traderAddr].withdrawAddr;
if (withdrawAddr == 0) withdrawAddr = traderAddr;
withdrawAddr.transfer(truncatedWei);
emit WithdrawEvent(traderAddr, 0, "ETH", uint64(amountE8), exeStatus.lastOperationIndex);
}
// Withdraw token (other than ETH) from the contract.
function withdrawToken(address traderAddr, uint16 tokenCode) external {
if (traderAddr == 0) revert();
if (tokenCode == 0) revert(); // this function does not handle ETH
if (msg.data.length != 4 + 32 + 32) revert(); // length condition of param count
TokenInfo memory tokenInfo = tokens[tokenCode];
if (tokenInfo.scaleFactor == 0) revert(); // unsupported token
uint176 accountKey = uint176(tokenCode) << 160 | uint176(traderAddr);
uint amountE8 = accounts[accountKey].pendingWithdrawE8;
if (amountE8 == 0) return;
// Write back to storage before making the transfer.
accounts[accountKey].pendingWithdrawE8 = 0;
uint truncatedAmount = amountE8 * uint(tokenInfo.scaleFactor) / 10**8;
address withdrawAddr = traders[traderAddr].withdrawAddr;
if (withdrawAddr == 0) withdrawAddr = traderAddr;
if (!Token(tokenInfo.tokenAddr).transfer(withdrawAddr, truncatedAmount)) revert();
emit WithdrawEvent(traderAddr, tokenCode, tokens[tokenCode].symbol, uint64(amountE8),
exeStatus.lastOperationIndex);
}
function transferFee(uint16 tokenCode, uint64 amountE8, address toAddr) external {
if (msg.sender != admin) revert();
if (toAddr == 0) revert();
if (msg.data.length != 4 + 32 + 32 + 32) revert();
TokenAccount memory feeAccount = accounts[uint176(tokenCode) << 160];
uint64 withdrawE8 = feeAccount.pendingWithdrawE8;
if (amountE8 < withdrawE8) {
withdrawE8 = amountE8;
}
feeAccount.pendingWithdrawE8 -= withdrawE8;
accounts[uint176(tokenCode) << 160] = feeAccount;
TokenInfo memory tokenInfo = tokens[tokenCode];
uint originalAmount = uint(withdrawE8) * uint(tokenInfo.scaleFactor) / 10**8;
if (tokenCode == 0) { // ETH
toAddr.transfer(originalAmount);
} else {
if (!Token(tokenInfo.tokenAddr).transfer(toAddr, originalAmount)) revert();
}
emit TransferFeeEvent(tokenCode, withdrawE8, toAddr);
}
function exeSequence(uint header, uint[] body) external {
if (msg.sender != admin) revert();
uint64 nextOperationIndex = uint64(header);
if (nextOperationIndex != exeStatus.lastOperationIndex + 1) revert(); // check index
uint64 newLogicTimeSec = uint64(header >> 64);
if (newLogicTimeSec < exeStatus.logicTimeSec) revert();
for (uint i = 0; i < body.length; nextOperationIndex++) {
uint bits = body[i];
uint opcode = bits & 0xFFFF;
bits >>= 16;
if ((opcode >> 8) != 0xDE) revert(); // check the magic number
// ConfirmDeposit: <depositIndex>(64)
if (opcode == 0xDE01) {
confirmDeposit(uint64(bits));
i += 1;
continue;
}
// InitiateWithdraw: <amountE8>(64) <tokenCode>(16) <traderAddr>(160)
if (opcode == 0xDE02) {
initiateWithdraw(uint176(bits), uint64(bits >> 176));
i += 1;
continue;
}
//-------- The rest operation types are allowed only when the market is active ---------
if (marketStatus != ACTIVE) revert();
// MatchOrders
if (opcode == 0xDE03) {
uint8 v1 = uint8(bits);
bits >>= 8; // bits is now the key of the maker order
Order memory makerOrder;
if (v1 == 0) { // the order is already in storage
if (i + 1 >= body.length) revert(); // at least 1 body element left
makerOrder = orders[uint224(bits)];
i += 1;
} else {
if (orders[uint224(bits)].pairId != 0) revert(); // the order must not be already in storage
if (i + 4 >= body.length) revert(); // at least 4 body elements left
makerOrder = parseNewOrder(uint224(bits) /*makerOrderKey*/, v1, body, i);
i += 4;
}
uint8 v2 = uint8(body[i]);
uint224 takerOrderKey = uint224(body[i] >> 8);
Order memory takerOrder;
if (v2 == 0) { // the order is already in storage
takerOrder = orders[takerOrderKey];
i += 1;
} else {
if (orders[takerOrderKey].pairId != 0) revert(); // the order must not be already in storage
if (i + 3 >= body.length) revert(); // at least 3 body elements left
takerOrder = parseNewOrder(takerOrderKey, v2, body, i);
i += 4;
}
matchOrder(uint224(bits) /*makerOrderKey*/, makerOrder, takerOrderKey, takerOrder);
continue;
}
// HardCancelOrder: <nonce>(64) <traderAddr>(160)
if (opcode == 0xDE04) {
hardCancelOrder(uint224(bits) /*orderKey*/);
i += 1;
continue;
}
// SetFeeRates: <withdrawFeeRateE4>(16) <takerFeeRateE4>(16) <makerFeeRateE4>(16)
if (opcode == 0xDE05) {
setFeeRates(uint16(bits), uint16(bits >> 16), uint16(bits >> 32));
i += 1;
continue;
}
// SetFeeRebatePercent: <rebatePercent>(8) <traderAddr>(160)
if (opcode == 0xDE06) {
setFeeRebatePercent(address(bits) /*traderAddr*/, uint8(bits >> 160) /*rebatePercent*/);
i += 1;
continue;
}
} // for loop
setExeStatus(newLogicTimeSec, nextOperationIndex - 1);
} // function exeSequence
//------------------------------ Public Functions: -----------------------------------------------
// Set token information.
function setTokenInfo(uint16 tokenCode, string symbol, address tokenAddr, uint64 scaleFactor,
uint minDeposit) public {
if (msg.sender != admin) revert();
if (marketStatus != ACTIVE) revert();
if (scaleFactor == 0) revert();
TokenInfo memory info = tokens[tokenCode];
if (info.scaleFactor != 0) { // this token already exists
// For an existing token only the minDeposit field can be updated.
tokens[tokenCode].minDeposit = minDeposit;
emit SetTokenInfoEvent(tokenCode, info.symbol, info.tokenAddr, info.scaleFactor, minDeposit);
return;
}
tokens[tokenCode].symbol = symbol;
tokens[tokenCode].tokenAddr = tokenAddr;
tokens[tokenCode].scaleFactor = scaleFactor;
tokens[tokenCode].minDeposit = minDeposit;
emit SetTokenInfoEvent(tokenCode, symbol, tokenAddr, scaleFactor, minDeposit);
}
//------------------------------ Private Functions: ----------------------------------------------
function setDeposits(uint64 depositIndex, address traderAddr, uint16 tokenCode, uint64 amountE8) private {
deposits[depositIndex].traderAddr = traderAddr;
deposits[depositIndex].tokenCode = tokenCode;
deposits[depositIndex].pendingAmountE8 = amountE8;
}
function setExeStatus(uint64 logicTimeSec, uint64 lastOperationIndex) private {
exeStatus.logicTimeSec = logicTimeSec;
exeStatus.lastOperationIndex = lastOperationIndex;
}
function confirmDeposit(uint64 depositIndex) private {
Deposit memory deposit = deposits[depositIndex];
uint176 accountKey = (uint176(deposit.tokenCode) << 160) | uint176(deposit.traderAddr);
TokenAccount memory account = accounts[accountKey];
// Check that pending amount is non-zero and no overflow would happen.
if (account.balanceE8 + deposit.pendingAmountE8 <= account.balanceE8) revert();
account.balanceE8 += deposit.pendingAmountE8;
deposits[depositIndex].pendingAmountE8 = 0;
accounts[accountKey].balanceE8 += deposit.pendingAmountE8;
emit ConfirmDepositEvent(deposit.traderAddr, deposit.tokenCode, account.balanceE8);
}
function initiateWithdraw(uint176 tokenAccountKey, uint64 amountE8) private {
uint64 balanceE8 = accounts[tokenAccountKey].balanceE8;
uint64 pendingWithdrawE8 = accounts[tokenAccountKey].pendingWithdrawE8;
if (balanceE8 < amountE8 || amountE8 == 0) revert();
balanceE8 -= amountE8;
uint64 feeE8 = calcFeeE8(amountE8, withdrawFeeRateE4, address(tokenAccountKey));
amountE8 -= feeE8;
if (pendingWithdrawE8 + amountE8 < amountE8) revert(); // check overflow
pendingWithdrawE8 += amountE8;
accounts[tokenAccountKey].balanceE8 = balanceE8;
accounts[tokenAccountKey].pendingWithdrawE8 = pendingWithdrawE8;
// Note that the fee account has a dummy trader address of 0.
if (accounts[tokenAccountKey & (0xffff << 160)].pendingWithdrawE8 + feeE8 >= feeE8) { // no overflow
accounts[tokenAccountKey & (0xffff << 160)].pendingWithdrawE8 += feeE8;
}
emit InitiateWithdrawEvent(address(tokenAccountKey), uint16(tokenAccountKey >> 160) /*tokenCode*/,
amountE8, pendingWithdrawE8);
}
function getDealInfo(uint32 pairId, uint64 priceE8, uint64 amount1E8, uint64 amount2E8)
private pure returns (DealInfo deal) {
deal.stockCode = uint16(pairId);
deal.cashCode = uint16(pairId >> 16);
if (deal.stockCode == deal.cashCode) revert(); // we disallow homogeneous trading
deal.stockDealAmountE8 = amount1E8 < amount2E8 ? amount1E8 : amount2E8;
uint cashDealAmountE8 = uint(priceE8) * uint(deal.stockDealAmountE8) / 10**8;
if (cashDealAmountE8 >= 2**64) revert();
deal.cashDealAmountE8 = uint64(cashDealAmountE8);
}
function calcFeeE8(uint64 amountE8, uint feeRateE4, address traderAddr)
private view returns (uint64) {
uint feeE8 = uint(amountE8) * feeRateE4 / 10000;
feeE8 -= feeE8 * uint(traders[traderAddr].feeRebatePercent) / 100;
return uint64(feeE8);
}
function settleAccounts(DealInfo deal, address traderAddr, uint feeRateE4, bool isBuyer) private {
uint16 giveTokenCode = isBuyer ? deal.cashCode : deal.stockCode;
uint16 getTokenCode = isBuyer ? deal.stockCode : deal.cashCode;
uint64 giveAmountE8 = isBuyer ? deal.cashDealAmountE8 : deal.stockDealAmountE8;
uint64 getAmountE8 = isBuyer ? deal.stockDealAmountE8 : deal.cashDealAmountE8;
uint176 giveAccountKey = uint176(giveTokenCode) << 160 | uint176(traderAddr);
uint176 getAccountKey = uint176(getTokenCode) << 160 | uint176(traderAddr);
uint64 feeE8 = calcFeeE8(getAmountE8, feeRateE4, traderAddr);
getAmountE8 -= feeE8;
// Check overflow.
if (accounts[giveAccountKey].balanceE8 < giveAmountE8) revert();
if (accounts[getAccountKey].balanceE8 + getAmountE8 < getAmountE8) revert();
// Write storage.
accounts[giveAccountKey].balanceE8 -= giveAmountE8;
accounts[getAccountKey].balanceE8 += getAmountE8;
if (accounts[uint176(getTokenCode) << 160].pendingWithdrawE8 + feeE8 >= feeE8) { // no overflow
accounts[uint176(getTokenCode) << 160].pendingWithdrawE8 += feeE8;
}
}
function setOrders(uint224 orderKey, uint32 pairId, uint8 action, uint8 ioc,
uint64 priceE8, uint64 amountE8, uint64 expireTimeSec) private {
orders[orderKey].pairId = pairId;
orders[orderKey].action = action;
orders[orderKey].ioc = ioc;
orders[orderKey].priceE8 = priceE8;
orders[orderKey].amountE8 = amountE8;
orders[orderKey].expireTimeSec = expireTimeSec;
}
function matchOrder(uint224 makerOrderKey, Order makerOrder,
uint224 takerOrderKey, Order takerOrder) private {
// Check trading conditions.
if (marketStatus != ACTIVE) revert();
if (makerOrderKey == takerOrderKey) revert(); // the two orders must not have the same key
if (makerOrder.pairId != takerOrder.pairId) revert();
if (makerOrder.action == takerOrder.action) revert();
if (makerOrder.priceE8 == 0 || takerOrder.priceE8 == 0) revert();
if (makerOrder.action == 0 && makerOrder.priceE8 < takerOrder.priceE8) revert();
if (takerOrder.action == 0 && takerOrder.priceE8 < makerOrder.priceE8) revert();
if (makerOrder.amountE8 == 0 || takerOrder.amountE8 == 0) revert();
if (makerOrder.expireTimeSec <= exeStatus.logicTimeSec) revert();
if (takerOrder.expireTimeSec <= exeStatus.logicTimeSec) revert();
DealInfo memory deal = getDealInfo(
makerOrder.pairId, makerOrder.priceE8, makerOrder.amountE8, takerOrder.amountE8);
// Update accounts.
settleAccounts(deal, address(makerOrderKey), makerFeeRateE4, (makerOrder.action == 0));
settleAccounts(deal, address(takerOrderKey), takerFeeRateE4, (takerOrder.action == 0));
// Update orders.
if (makerOrder.ioc == 1) { // IOC order
makerOrder.amountE8 = 0;
} else {
makerOrder.amountE8 -= deal.stockDealAmountE8;
}
if (takerOrder.ioc == 1) { // IOC order
takerOrder.amountE8 = 0;
} else {
takerOrder.amountE8 -= deal.stockDealAmountE8;
}
// Write orders back to storage.
setOrders(makerOrderKey, makerOrder.pairId, makerOrder.action, makerOrder.ioc,
makerOrder.priceE8, makerOrder.amountE8, makerOrder.expireTimeSec);
setOrders(takerOrderKey, takerOrder.pairId, takerOrder.action, takerOrder.ioc,
takerOrder.priceE8, takerOrder.amountE8, takerOrder.expireTimeSec);
emit MatchOrdersEvent(address(makerOrderKey), uint64(makerOrderKey >> 160) /*nonce*/,
address(takerOrderKey), uint64(takerOrderKey >> 160) /*nonce*/);
}
function hardCancelOrder(uint224 orderKey) private {
orders[orderKey].pairId = 0xFFFFFFFF;
orders[orderKey].amountE8 = 0;
emit HardCancelOrderEvent(address(orderKey) /*traderAddr*/, uint64(orderKey >> 160) /*nonce*/);
}
function setFeeRates(uint16 makerE4, uint16 takerE4, uint16 withdrawE4) private {
if (makerE4 > MAX_FEE_RATE_E4) revert();
if (takerE4 > MAX_FEE_RATE_E4) revert();
if (withdrawE4 > MAX_FEE_RATE_E4) revert();
makerFeeRateE4 = makerE4;
takerFeeRateE4 = takerE4;
withdrawFeeRateE4 = withdrawE4;
emit SetFeeRatesEvent(makerE4, takerE4, withdrawE4);
}
function setFeeRebatePercent(address traderAddr, uint8 feeRebatePercent) private {
if (feeRebatePercent > 100) revert();
traders[traderAddr].feeRebatePercent = feeRebatePercent;
emit SetFeeRebatePercentEvent(traderAddr, feeRebatePercent);
}
function parseNewOrder(uint224 orderKey, uint8 v, uint[] body, uint i) private view returns (Order) {
// bits: <expireTimeSec>(64) <amountE8>(64) <priceE8>(64) <ioc>(8) <action>(8) <pairId>(32)
uint240 bits = uint240(body[i + 1]);
uint64 nonce = uint64(orderKey >> 160);
address traderAddr = address(orderKey);
if (traderAddr == 0) revert(); // check zero addr early since `ecrecover` returns 0 on error
// verify the signature of the trader
bytes32 hash1 = keccak256("\x19Ethereum Signed Message:\n70DEx2 Order: ", address(this), nonce, bits);
if (traderAddr != ecrecover(hash1, v, bytes32(body[i + 2]), bytes32(body[i + 3]))) {
bytes32 hashValues = keccak256("DEx2 Order", address(this), nonce, bits);
bytes32 hash2 = keccak256(HASHTYPES, hashValues);
if (traderAddr != ecrecover(hash2, v, bytes32(body[i + 2]), bytes32(body[i + 3]))) revert();
}
Order memory order;
order.pairId = uint32(bits); bits >>= 32;
order.action = uint8(bits); bits >>= 8;
order.ioc = uint8(bits); bits >>= 8;
order.priceE8 = uint64(bits); bits >>= 64;
order.amountE8 = uint64(bits); bits >>= 64;
order.expireTimeSec = uint64(bits);
return order;
}
} // contract | Withdraw token (other than ETH) from the contract. Write back to storage before making the transfer. | function withdrawToken(address traderAddr, uint16 tokenCode) external {
if (traderAddr == 0) revert();
TokenInfo memory tokenInfo = tokens[tokenCode];
uint176 accountKey = uint176(tokenCode) << 160 | uint176(traderAddr);
uint amountE8 = accounts[accountKey].pendingWithdrawE8;
if (amountE8 == 0) return;
accounts[accountKey].pendingWithdrawE8 = 0;
uint truncatedAmount = amountE8 * uint(tokenInfo.scaleFactor) / 10**8;
address withdrawAddr = traders[traderAddr].withdrawAddr;
if (withdrawAddr == 0) withdrawAddr = traderAddr;
if (!Token(tokenInfo.tokenAddr).transfer(withdrawAddr, truncatedAmount)) revert();
emit WithdrawEvent(traderAddr, tokenCode, tokens[tokenCode].symbol, uint64(amountE8),
exeStatus.lastOperationIndex);
}
| 6,262,521 | [
1,
1190,
9446,
1147,
261,
3011,
2353,
512,
2455,
13,
628,
326,
6835,
18,
2598,
1473,
358,
2502,
1865,
10480,
326,
7412,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
598,
9446,
1345,
12,
2867,
1284,
765,
3178,
16,
2254,
2313,
1147,
1085,
13,
3903,
288,
203,
565,
309,
261,
313,
1143,
3178,
422,
374,
13,
15226,
5621,
203,
203,
565,
3155,
966,
3778,
1147,
966,
273,
2430,
63,
2316,
1085,
15533,
203,
203,
565,
2254,
28493,
2236,
653,
273,
2254,
28493,
12,
2316,
1085,
13,
2296,
25430,
571,
2254,
28493,
12,
313,
1143,
3178,
1769,
203,
565,
2254,
3844,
41,
28,
273,
9484,
63,
4631,
653,
8009,
9561,
1190,
9446,
41,
28,
31,
203,
565,
309,
261,
8949,
41,
28,
422,
374,
13,
327,
31,
203,
203,
565,
9484,
63,
4631,
653,
8009,
9561,
1190,
9446,
41,
28,
273,
374,
31,
203,
203,
565,
2254,
15282,
6275,
273,
3844,
41,
28,
380,
2254,
12,
2316,
966,
18,
5864,
6837,
13,
342,
1728,
636,
28,
31,
203,
565,
1758,
598,
9446,
3178,
273,
1284,
6794,
63,
313,
1143,
3178,
8009,
1918,
9446,
3178,
31,
203,
565,
309,
261,
1918,
9446,
3178,
422,
374,
13,
598,
9446,
3178,
273,
1284,
765,
3178,
31,
203,
565,
309,
16051,
1345,
12,
2316,
966,
18,
2316,
3178,
2934,
13866,
12,
1918,
9446,
3178,
16,
15282,
6275,
3719,
15226,
5621,
203,
565,
3626,
3423,
9446,
1133,
12,
313,
1143,
3178,
16,
1147,
1085,
16,
2430,
63,
2316,
1085,
8009,
7175,
16,
2254,
1105,
12,
8949,
41,
28,
3631,
203,
15604,
15073,
1482,
18,
2722,
2988,
1016,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xEB0D32045809B888A5B04c5F8Ba482173eF9F1f7/sources/BaseToken.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 Context {
pragma solidity ^0.8.19;
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 8,345,193 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
1772,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3657,
31,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
745,
892,
13,
288,
203,
3639,
327,
1234,
18,
892,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.22; //Defino a versão do programa Solidity
contract StreamingService {
//Defino o contrato
struct Listener {
//Crio a estrutura de um ouvinte que possui um endereço e um map(música => quantidade de execuções)
address user;
mapping(uint256 => uint256) music;
}
struct Musician {
//Crio a estrutura de um Músico que possui um endereço, um map(música => quantidade de execuções) e total de execuções do artista
address cod;
mapping(uint256 => uint256) music;
uint256 totalPlays;
}
Listener[] listeners; //Crio um array de ouvintes
Musician[] musicians; //Crio um array de músicos
function addMusic(uint256 cod_music, address addr_musician) public {
//Função de adicionar música ao contrato
bool haveMusician = false; //Checar se o músico da música já está cadastrado
for (uint256 i = 0; i < musicians.length; i++) {
//Faço uma busca no array de músicos
if (musicians[i].cod == addr_musician) {
//Se achar o músico
haveMusician = true; //Então o músico já está cadastrado
musicians[i].music[cod_music] = 1; //Crio uma nova música
}
}
if (!haveMusician) {
//Se o músico não estiver cadastrado
musicians.push(
Musician({cod: addr_musician, totalPlays: 0}) //O contrato automaticamente cadastra o músico com um endereço e o total de execuções
);
musicians[musicians.length - 1].music[cod_music] = 1; //E cria um map com a música cadastrada
}
}
//Função para ouvir uma música
function listenMusic(uint256 cod_music) public {
bool haveMusic = false; //Testador para verificar se a música existe
for (uint256 i = 0; i < musicians.length; i++) {
//Percorre o array de músicos
if (musicians[i].music[cod_music] != 0) {
//Se a música estiver cadastrada
musicians[i].music[cod_music]++; //Some 1 ao número de execuções de músicos
musicians[i].totalPlays++; //Some 1 ao total de execuções do artista
haveMusic = true; //Confirma que a música está cadastrada
break; //Encerra a busca
}
}
if (haveMusic) {
//Se a música estiver cadastrada
bool haveUser = false; //Testador para verificar de o usuário existe
for (uint256 j = 0; j < listeners.length; j++) {
//Percorre o array de ouvintes
if (listeners[j].user == msg.sender) {
//Verifica se o encontra registro do ouvinte
haveUser = true; //Se sim, então confirma que há usuário
listeners[j].music[cod_music]++; //Adiciono 1 ao número de execuções do usuário a música
break; //Encerro a busca
}
}
if (!haveUser) {
//Se o usuário não estiver cadastrado
listeners.push(
Listener({user: msg.sender}) //O contrato cadastra automaticamente com o endereço
);
listeners[listeners.length - 1].music[cod_music]++; //Adiciono a música na lista de músicas reproduzidas pelo usuário
}
}
}
//Função para mostrar o status geral de uma música
function musicStats(uint256 cod_music) public view returns (uint256 qntd){
qntd = 0;
for (uint256 i = 0; i < musicians.length; i++) {
if (musicians[i].music[cod_music] != 0) {
qntd = musicians[i].music[cod_music] - 1;
}
}
}
//Função para mostrar o status geral de um artista
function musicianStats(address addr_musician) public view returns (uint256 qntd){
qntd = 0;
for (uint256 i = 0; i < musicians.length; i++) {
if (musicians[i].cod == addr_musician) {
qntd = musicians[i].totalPlays;
}
}
}
//Função para ver status da música por ouvinte
function userStats(uint256 cod_music) public view returns (uint256 qntd){
qntd = 0;
for (uint256 i = 0; i < listeners.length; i++) {
if (listeners[i].user == msg.sender) {
qntd = listeners[i].music[cod_music];
break;
}
}
}
//Função só pra testes
function getListen(uint256 cod_music, uint256 qtd) public view returns (uint qntd){
for (uint256 i = 0; i < musicians.length; i++) {
if (musicians[i].music[cod_music] == qtd + 1) {
return qtd;
}
}
return 0;
}
} | Crio a estrutura de um ouvinte que possui um endereço e um map(música => quantidade de execuções) | struct Listener {
address user;
mapping(uint256 => uint256) music;
}
| 1,840,606 | [
1,
39,
566,
83,
279,
5001,
313,
322,
21401,
443,
9570,
320,
16303,
474,
73,
6597,
949,
87,
4881,
9570,
679,
822,
132,
105,
83,
425,
9570,
852,
12,
81,
132,
123,
87,
26433,
516,
225,
10251,
30681,
443,
1196,
89,
132,
105,
132,
118,
281,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
10652,
288,
203,
3639,
1758,
729,
31,
203,
3639,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
26225,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x1E2C2102cf8EfCaAAf20fFe926469EC7cD0d0f6E/sources/browser/MiniswapV2Factory.sol | single check is sufficient
| require(getPair[token0][token1] == address(0), 'MiniswapV2: PAIR_EXISTS'); | 2,983,077 | [
1,
7526,
866,
353,
18662,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
588,
4154,
63,
2316,
20,
6362,
2316,
21,
65,
422,
1758,
12,
20,
3631,
296,
2930,
291,
91,
438,
58,
22,
30,
15662,
7937,
67,
21205,
8284,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x28fbe43b52544a3947309768e11E4c1AebFDbD92/sources/src/token/ERC1155/extensions/lockable/IERC1155LockableExtension.sol | * @dev Extension of {ERC1155} that allows other facets from the diamond to lock the tokens./ | interface IERC1155LockableExtension {
function lockByFacet(
address account,
uint256 id,
uint256 amount
) external;
function lockByFacet(
address[] memory accounts,
uint256[] memory ids,
uint256[] memory amounts
) external;
function unlockByFacet(
address account,
uint256 id,
uint256 amount
) external;
function unlockByFacet(
address[] memory accounts,
uint256[] memory ids,
uint256[] memory amounts
) external;
}
| 1,894,987 | [
1,
3625,
434,
288,
654,
39,
2499,
2539,
97,
716,
5360,
1308,
21681,
628,
326,
4314,
301,
1434,
358,
2176,
326,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
2499,
2539,
2531,
429,
3625,
288,
203,
565,
445,
2176,
858,
11137,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
2254,
5034,
612,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
2176,
858,
11137,
12,
203,
3639,
1758,
8526,
3778,
9484,
16,
203,
3639,
2254,
5034,
8526,
3778,
3258,
16,
203,
3639,
2254,
5034,
8526,
3778,
30980,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
7186,
858,
11137,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
2254,
5034,
612,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
7186,
858,
11137,
12,
203,
3639,
1758,
8526,
3778,
9484,
16,
203,
3639,
2254,
5034,
8526,
3778,
3258,
16,
203,
3639,
2254,
5034,
8526,
3778,
30980,
203,
565,
262,
3903,
31,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at BscScan.com on 2022-03-31
*/
// SPDX-License-Identifier: MIT
// 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/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/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: @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/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();
}
}
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/NFTtoken1.sol
pragma solidity ^0.8.0;
contract XpertioNFT is Context, ERC721Enumerable, Ownable {
address payable wallet;
uint256 public fee;
uint256 counterNFTs;
uint counterTokensERC20;
bool public paused;
struct tokenERC20 {
IERC20 token;
uint fee;
}
mapping(uint => tokenERC20) public ERC20Tokens;
mapping (uint256 => string) private _tokenURIs;
struct NftItem {
address payable owner;
uint256 id;
uint256 price;
uint idERC20;
bool onSale;
}
mapping(uint256 => NftItem) public Nfts;
event Mint(address indexed owner, uint256 id, string uri);
event SellNft(address indexed owner, uint256 id, uint256 price);
event PriceUpdate(address indexed owner, uint256 id, uint256 oldPrice, uint256 newPrice);
event Purchase(address indexed oldOwner, address indexed newOwner, uint256 id, uint256 price, string uri);
event CancelSale(address indexed owner, uint256 id);
event TransferNft(address indexed oldOwner, address indexed newOwner, uint256 id, string uri);
constructor() ERC721("XPERTIO", "XPTO") {
fee = 2500000000000000000; //2.5
paused = false;
wallet = payable(msg.sender);
ERC20Tokens[counterTokensERC20] = tokenERC20(IERC20(address(this)), fee);
counterTokensERC20++;
}
/* Public */
function addTokenERC20(address _token, uint _fee) public onlyOwner{
require(isContract(_token));
require(_fee >= 0);
// recorro el mapping para ver si esta el token previamente
for(uint i ; i < counterTokensERC20; i++){
if(ERC20Tokens[i].token == IERC20(_token)){
revert("The token already exists");
}
}
ERC20Tokens[counterTokensERC20] = tokenERC20(IERC20(_token), _fee);
counterTokensERC20++;
}
function updateFeeTokenERC20(uint _id, uint _fee) public onlyOwner{
ERC20Tokens[_id].fee = _fee;
}
function updateAddressTokenERC20(uint _id, address _addr) public onlyOwner{
ERC20Tokens[_id].token = IERC20(_addr);
}
function isContract(address _contractID) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(_contractID)
}
return size > 0;
}
function mint(address _to, string memory _uri ) public {
require(!paused);
uint256 id = counterNFTs;
_mint(_to, id);
_tokenURIs[id] = _uri;
Nfts[id] = NftItem(payable(_to), id, 0, 0, false);
counterNFTs++;
emit Mint(_to, id, _uri);
}
function sellNft(uint _id, uint _price, uint _idTokenERC20) public {
require(Nfts[_id].owner == _msgSender());
require(checkIfNftIsOnSell(_id) == false);
require(_price > 0);
approve(address(this), _id);
transferFrom(_msgSender(), address(this), _id);
Nfts[_id].price = _price;
Nfts[_id].idERC20 = _idTokenERC20;
Nfts[_id].onSale = true;
emit SellNft(_msgSender(), _id, _price);
}
function changePriceNft(uint256 _id, uint256 _newPrice) public {
require(Nfts[_id].owner == _msgSender());
require(checkIfNftIsOnSell(_id) == true);
uint oldPrice = Nfts[_id].price;
Nfts[_id].price = _newPrice;
emit PriceUpdate(_msgSender(), _id, oldPrice, _newPrice);
}
function cancelSale(uint256 _id) public {
require(Nfts[_id].owner == _msgSender());
require(checkIfNftIsOnSell(_id) == true);
Nfts[_id].price = 0;
Nfts[_id].idERC20 = 0;
Nfts[_id].onSale = false;
// asigno el nft al dueno
_safeTransfer(address(this), _msgSender(), _id, "");
emit CancelSale(_msgSender(), _id);
}
function transferNft(address _to, uint256 _id) public {
require(Nfts[_id].owner == _msgSender());
// asigno el nft al nuevo dueno
if(checkIfNftIsOnSell(_id)){
_safeTransfer(address(this), _to, _id, "");
}else{
_safeTransfer(_msgSender(), _to, _id, "");
}
// actualizo el mapping
address oldOwner = Nfts[_id].owner;
Nfts[_id].owner = payable(_to);
Nfts[_id].price = 0;
Nfts[_id].idERC20 = 0;
Nfts[_id].onSale = false;
emit TransferNft(oldOwner, _to, _id, _tokenURIs[_id]);
}
function buyNft(uint256 _id, uint _price) external payable{
require(
checkIfNftIsOnSell(_id) == true,
"BUY: NFT is not for sale"
);
require(
Nfts[_id].owner != _msgSender(),
"BUY: seriusly? why you wanna buy your own token?"
);
if(Nfts[_id].idERC20 == 0){
require(
msg.value >= Nfts[_id].price,
"BUY: the amount that you send is less than the required"
);
}else if(Nfts[_id].idERC20 > 0){
require(
ERC20Tokens[Nfts[_id].idERC20].token.balanceOf( _msgSender()) >= _price,
"BUY: you dont have tokens enough"
);
require(
_price >= Nfts[_id].price,
"BUY: the amount that you send is less than the required"
);
}
uint feeToken = ERC20Tokens[Nfts[_id].idERC20].fee;
uint256 fees;
uint256 amountToOwner;
if(Nfts[_id].idERC20 == 0){
fees = ((msg.value * feeToken) / (100 * 10 ** 18));
amountToOwner = msg.value - fees;
Nfts[_id].owner.transfer(amountToOwner);
wallet.transfer(address(this).balance);
}else{
fees = ((_price * feeToken) / (100 * 10 ** 18));
amountToOwner = _price - fees;
ERC20Tokens[Nfts[_id].idERC20].token.transferFrom(_msgSender(), address(this), _price);
ERC20Tokens[Nfts[_id].idERC20].token.transfer(Nfts[_id].owner, amountToOwner);
ERC20Tokens[Nfts[_id].idERC20].token.transfer(wallet, ERC20Tokens[Nfts[_id].idERC20].token.balanceOf(address(this)));
}
// asigno el nft al nuevo dueno
_safeTransfer(address(this), _msgSender(), _id, "");
// actualizo el mapping
address oldOwner = Nfts[_id].owner;
Nfts[_id].owner = payable(_msgSender());
Nfts[_id].price = 0;
Nfts[_id].idERC20 = 0;
Nfts[_id].onSale = false;
emit Purchase(oldOwner, _msgSender(), _id, _price, _tokenURIs[_id]);
}
function checkIfNftIsOnSell(uint256 _id) public view returns (bool) {
bool flag;
if (Nfts[_id].onSale == true) {
flag = true;
}
return flag;
}
function getAllNfts() public view returns (NftItem[] memory) {
NftItem[] memory Tempo = new NftItem[](counterNFTs);
for (uint256 i; i < counterNFTs; i++) {
Tempo[i] = Nfts[i];
}
return Tempo;
}
function tokenURI(uint256 _id) public view virtual override returns (string memory) {
require(
_exists(_id),
"ERC721Metadata: URI query for nonexistent token"
);
return bytes(_tokenURIs[_id]).length > 0 ? _tokenURIs[_id] : "";
}
function myBalance() public view returns (uint256) {
return _msgSender().balance;
}
function getPriceOfNft(uint256 _id) public view returns (uint256) {
return Nfts[_id].price;
}
function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
/* Only Owner */
function setFee(uint256 _newFee) public onlyOwner {
fee = _newFee;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setWallet(address payable _newWallet) public onlyOwner {
wallet = _newWallet;
}
function withdraw() public payable onlyOwner {
require(payable(_msgSender()).send(address(this).balance));
}
} | asigno el nft al nuevo dueno | function transferNft(address _to, uint256 _id) public {
require(Nfts[_id].owner == _msgSender());
if(checkIfNftIsOnSell(_id)){
_safeTransfer(address(this), _to, _id, "");
_safeTransfer(_msgSender(), _to, _id, "");
}
Nfts[_id].owner = payable(_to);
Nfts[_id].price = 0;
Nfts[_id].idERC20 = 0;
Nfts[_id].onSale = false;
emit TransferNft(oldOwner, _to, _id, _tokenURIs[_id]);
}
| 643,149 | [
1,
345,
724,
83,
415,
290,
1222,
524,
290,
344,
12307,
9978,
5764,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
50,
1222,
12,
2867,
389,
869,
16,
2254,
5034,
389,
350,
13,
1071,
288,
203,
3639,
2583,
12,
50,
1222,
87,
63,
67,
350,
8009,
8443,
422,
389,
3576,
12021,
10663,
203,
203,
3639,
309,
12,
1893,
2047,
50,
1222,
2520,
1398,
55,
1165,
24899,
350,
3719,
95,
203,
5411,
389,
4626,
5912,
12,
2867,
12,
2211,
3631,
389,
869,
16,
389,
350,
16,
1408,
1769,
203,
5411,
389,
4626,
5912,
24899,
3576,
12021,
9334,
389,
869,
16,
389,
350,
16,
1408,
1769,
203,
3639,
289,
203,
540,
203,
3639,
423,
1222,
87,
63,
67,
350,
8009,
8443,
273,
8843,
429,
24899,
869,
1769,
203,
3639,
423,
1222,
87,
63,
67,
350,
8009,
8694,
273,
374,
31,
203,
3639,
423,
1222,
87,
63,
67,
350,
8009,
350,
654,
39,
3462,
273,
374,
31,
203,
3639,
423,
1222,
87,
63,
67,
350,
8009,
265,
30746,
273,
629,
31,
203,
203,
3639,
3626,
12279,
50,
1222,
12,
1673,
5541,
16,
389,
869,
16,
389,
350,
16,
389,
2316,
1099,
2520,
63,
67,
350,
19226,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.0;
contract Hackday {
struct Item {
uint id;
string name;
uint quantity;
string picture;
uint price;
}
// Read/write ItemsForSale
mapping(uint => Item) public itemsForSale;
struct User {
uint id;
string name;
string picture;
Item[] ownedItems;
}
mapping(uint => User) public users;
function initializeItemsForSale () private {
itemsForSale[1] = Item(1,"item-1", 3, "path-to-pic.png", 5);
itemsForSale[2] = Item(2,"item-2", 2, "path-to-pic.png", 4);
itemsForSale[3] = Item(3,"item-3", 4, "path-to-pic.png", 6);
}
function initializeUsers() private {
users[1] = User(1, "Pierre", "path-to-pic.png", new Item[](0));
users[2] = User(2, "Matt", "path-to-pic.png", new Item[](0));
users[3] = User(3, "Shuoyi", "path-to-pic.png", new Item[](0));
users[4] = User(4, "Jyothi", "path-to-pic.png", new Item[](0));
users[5] = User(5, "Yi-Chi", "path-to-pic.png", new Item[](0));
}
function purchaseItem(uint itemId, uint quantity, uint userId) public {
itemsForSale[itemId].quantity = itemsForSale[itemId].quantity - quantity;
users[userId].ownedItems.push(Item(itemId, itemsForSale[itemId].name, quantity, itemsForSale[itemId].picture, itemsForSale[itemId].price));
}
function transactEther(uint originatingAccount, uint amount) private {
}
// Constructor
constructor () public {
initializeItemsForSale();
}
} | Read/write ItemsForSale | mapping(uint => Item) public itemsForSale;
| 12,917,754 | [
1,
1994,
19,
2626,
10240,
1290,
30746,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2874,
12,
11890,
516,
4342,
13,
1071,
1516,
1290,
30746,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x716744A30CD4bf6e4cfCCf7598f724BE5172d0B9/sources/wallet.sol | @dev Checks if the value is not zero. | modifier isNotZero(uint _value) {
require(_value != 0, "provided value cannot be zero");
_;
}
| 4,295,174 | [
1,
4081,
309,
326,
460,
353,
486,
3634,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
8827,
7170,
12,
11890,
389,
1132,
13,
288,
203,
3639,
2583,
24899,
1132,
480,
374,
16,
315,
29206,
460,
2780,
506,
3634,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x2Cf1D401Da3Bc79f9B1a791C9b538931248d8864/sources/MOONBASE.sol | set as devolper wallet
| devWallet = address(0xD90663F9AE5eF80bc7b0355ab14Ee577E5A3A4E3); | 4,470,492 | [
1,
542,
487,
4461,
355,
457,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
4461,
16936,
273,
1758,
12,
20,
17593,
29,
7677,
4449,
42,
29,
16985,
25,
73,
42,
3672,
13459,
27,
70,
4630,
2539,
378,
3461,
41,
73,
25,
4700,
41,
25,
37,
23,
37,
24,
41,
23,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//TG: https://t.me/catacult
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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);
}
}
/**
* @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);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
/* pragma solidity ^0.8.0; */
/* import "../IERC20.sol"; */
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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;
}
}
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface 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 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;
}
contract CataCult is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = true;
bool public swapEnabled = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = false;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// exlcude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Catacult", "CCULT") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 10;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 1;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 8_000_000 * 1e18; //
maxWallet = 24_000_000 * 1e18; //
swapTokensAtAmount = (totalSupply * 5) / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0xBEcB6531E0f7d982910ab51D0C5871C375F2213a);
devWallet = address(0xBEcB6531E0f7d982910ab51D0C5871C375F2213a);
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
//when sell
else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if (takeFee) {
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
// on buy
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success, ) = address(devWallet).call{value: ethForDev}("");
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("Catacult", "CCULT") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 10;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 1;
uint256 totalSupply = 1_000_000_000 * 1e18;
swapTokensAtAmount = (totalSupply * 5) / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0xBEcB6531E0f7d982910ab51D0C5871C375F2213a);
devWallet = address(0xBEcB6531E0f7d982910ab51D0C5871C375F2213a);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 6,895,441 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
39,
396,
71,
406,
3113,
315,
6743,
2274,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
576,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
576,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../Governance.sol";
contract TestGovernance is Governance {
event Received(address, uint256);
constructor(address t) {
// For this to work need to manually remove the `constant` keyword from the TellorVars contract.
TELLOR_ADDRESS = t;
}
receive() external payable {
emit Received(msg.sender, msg.value);
}
//allows the contract to recieve funds for gas via harhdat-impersonate account
fallback() external payable {
emit Received(msg.sender, msg.value);
}
}
| For this to work need to manually remove the `constant` keyword from the TellorVars contract. | constructor(address t) {
TELLOR_ADDRESS = t;
}
| 7,269,231 | [
1,
1290,
333,
358,
1440,
1608,
358,
10036,
1206,
326,
1375,
14384,
68,
4932,
628,
326,
29860,
280,
5555,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
268,
13,
225,
288,
203,
3639,
399,
21943,
916,
67,
15140,
273,
268,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import {GNXToken} from "../tokens/GNXToken.sol";
import {GNXNative} from "../tokens/GNXNative.sol";
import {GNXPoolFactory} from "./GNXPoolFactory.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// Upgradeables?
/**
* @title GNXPool - Liquidity trading pools for wrapped GNXToken and GNXNative
* @author Bailey de Villiers (https://github.com/itchysnake)
* @dev Liquidity pool derived from Uniswap-V1. To be used specifically with
* GNX Pool Factory, GNXToken, and GNXNative.
*/
interface IGNXPool {
function tokenReserve() external view returns (uint256);
function nativeReserve() external view returns (uint256);
function addLiquidity(uint256 tokenDeposit, uint256 nativeDeposit) external returns (uint256);
function removeLiquidity(uint256 amount) external returns (uint256, uint256);
function nativeToToken(uint256 nativeSold) external returns (uint256);
function tokenToNative(uint256 tokensSold) external returns (uint256);
function buyNative(uint256 minNative, uint256 tokensSold) external returns (uint256);
function buyTokens(uint256 minTokens, uint256 nativeSold) external returns (uint256);
function tokenSwap(uint256 tokensSold, uint256 minTokens, address GNXTokenAddress) external;
function _tokenSwap(uint256 minTokens, uint256 nativeSold, address recipient) external;
event liquidityChange(address indexed from, address indexed to, uint256 amount);
event Trade(address indexed trader, address output, uint256 inputAmount, uint256 outputAmount);
}
contract GNXPool is
ERC20,
IGNXPool {
GNXToken public token; // Wrapped GNXToken
GNXNative public native; // GNXNative token
GNXPoolFactory public factory; // Parent GNX pool factory
// Contract is an ERC20 to provide LP rewards
constructor(address _GNXToken, address _GNXNative) ERC20("GENEX-V1","GNXV1") {
require(_GNXToken != address(0), "GNX: invalid token address");
token = GNXToken(_GNXToken);
native = GNXNative(_GNXNative);
factory = GNXPoolFactory(msg.sender);
}
// View function for GNXToken reserve
//
// @notice View function for GNXTokens stored in this contract
//
// @return Amount of GNXNative held in this contract
function tokenReserve() public override(IGNXPool) view returns(uint256){
return token.balanceOf(address(this));
}
// View function for GNXNative reserve
//
// @notice View function for GNXNative stored in this contract.
//
// @return Amount of GNXNative held in this contract.
function nativeReserve() public override(IGNXPool) view returns(uint256){
return native.balanceOf(address(this));
}
// Ability to add liquidity to the pool (mints LP tokens)
//
// @notice Add liquidity of GNXToken and GNXNative to this trading pool. Users
// are rewarded in LP which can be exchanged for liquidity and trading accrued
// fees.
//
// @notice Liquidity of both tokens added must be equal. Technically only
// one param required but having two params for both tokens makes it clear
// that both are required to add liquidity.
//
// @dev ERC20 LP tokens are minted equal to the GNXNative deposit made.
// Required deposit amount must be calculated in front-end. Equal deposit
// is enforced by contract to prevent price manipulation.
//
// @param tokenDeposit Quantity of GNXToken deposited.
// @param nativeDeposit Quantity of GNXNative deposited.
//
// @return Quantity of LP tokens minted to msg.sender.
function addLiquidity(uint256 tokenDeposit, uint256 nativeDeposit) public override(IGNXPool) returns (uint256) {
// Iniital liquidity add
if (tokenReserve() == 0) {
// Pulling GNXToken
token.transferFrom(msg.sender, address(this), tokenDeposit);
// Pulling GNXNative
native.transferFrom(msg.sender, address(this), nativeDeposit);
// Sends LPs in exchange for initial deposit
uint256 _nativeReserve = nativeReserve();
_mint(msg.sender, _nativeReserve);
emit liquidityChange(msg.sender, address(this), _nativeReserve);
return _nativeReserve;
// Normal liquidity add
} else {
uint256 _nativeReserve = nativeReserve() - nativeDeposit;
uint256 _tokenReserve = tokenReserve();
uint256 tokenOutput = (nativeDeposit * _tokenReserve) / _nativeReserve;
require(nativeDeposit >= tokenOutput, "GNX: insufficient token amount"); // Maintains pool price
// Pulls GNXToken
token.transferFrom(msg.sender, address(this), tokenDeposit);
// Pulls GNXNative
native.transferFrom(msg.sender, address(this), nativeDeposit);
// Mints LP tokens
uint256 liquidityTokens = (totalSupply() * nativeDeposit) / _nativeReserve;
_mint(msg.sender, liquidityTokens);
emit liquidityChange(msg.sender, address(this), nativeDeposit);
return liquidityTokens;
}
}
// Exchange LPs for equal return of GNXToken and GNXNative.
//
// @notice Burn LP tokens in exchange for GNXNative and GNXTokens based
// on current reserves, and amount being submitted. Portion of accrued fees
// are also returned in the respective token. Potentially results in
// impermenant loss.
//
// @param amount Quantity of LP tokens submitted for exchange.
//
// @return Tuple of GNXNative output, and GNXToken output.
function removeLiquidity(uint256 amount) public override(IGNXPool) returns (uint256, uint256) {
require(amount > 0, "GNX: amount too low");
uint256 nativeOutput = (nativeReserve() * amount) / totalSupply();
uint256 tokenOutput = (tokenReserve() * amount) / totalSupply();
// returns an equal amount of GNXNative and GNXToken and burns LP tokens
_burn(msg.sender, amount);
token.transfer(msg.sender, tokenOutput);
native.transfer(msg.sender, nativeOutput);
emit liquidityChange(address(this), msg.sender, amount);
return (nativeOutput, tokenOutput);
}
// Private pricing function
//
// @notice Private function used to determine "price," or output amount
// of one of the two assets traded in the pool. Fee is set to 0.5% and
// is accrued in the token used as input.
//
// @dev Calculation is derived from uniswap's constant product AMM, x*y=k.
//
// @param inputAmount Quantity of tokens sent, or intend to be sent by user.
// @param inputReserve Quantity of output tokens stored in contract.
// @param outputReserve Quantity of output tokens stored in contract.
//
// @return Output token amount.
function getAmount(
uint256 inputAmount,
uint256 inputReserve,
uint256 outputReserve
) private pure returns(uint256) {
require(inputReserve > 0 && outputReserve > 0, "GNX: invalid reserves");
// 0.5% fee
uint256 inputAmountWithFee = inputAmount * 995;
uint256 numerator = inputAmountWithFee * outputReserve;
uint256 denominator = (inputReserve*1000) + inputAmountWithFee;
// Returns (outputAmount, totalFee)
return (numerator/denominator);
}
// Lookup function
//
// @notice Lookup function to call current price for selling GNXNative to
// receive GNXToken.
//
// @param nativeSold Quantity of GNXNative to be sold.
//
// @return Output GNXToken amount.
function nativeToToken(uint256 nativeSold) public view override(IGNXPool) returns (uint256) {
require(nativeSold > 0, "GNX: too few GNXNative");
uint256 _tokenReserve = tokenReserve();
uint256 _nativeReserve = nativeReserve();
return getAmount(nativeSold, _nativeReserve, _tokenReserve);
}
// Lookup function
//
// @notice Lookup function to call current price for selling GNXToken to
// receive GNXNative.
//
// @param tokensSold Quantity of GNXTokens to be sold.
//
// @return Output GNXNative amount.
function tokenToNative(uint256 tokensSold) public view override(IGNXPool) returns (uint256) {
require(tokensSold > 0, "GNX: too few GNXToken");
uint256 _tokenReserve = tokenReserve();
uint256 _nativeReserve = nativeReserve();
return getAmount(tokensSold, _tokenReserve, _nativeReserve);
}
// Private buy function
//
// @notice Private buy function which allows additional flexibility for
// public buyToken functions (or variations thereof).
//
// @dev Used to provide additional flexibility in the two other methods of
// tokens purchase. First method is generic purchase (buyTokens), while second
// is reserved for _tokenSwap allowing two tokens to be exchanged from pool
// to pool.
//
// @param minTokens Minimum number of tokens expected from output. Enforced
// in front-end to prevent price spoofing with bots.
// @param nativeSold Quantity of GNXNative sold.
// @param recipient Recipient of the output quantity of GNXTokens.
//
// @return Quantity of GNXTokens output.
function _buyTokens(
uint256 minTokens,
uint256 nativeSold,
address recipient
) private returns (uint256) {
uint256 _tokenReserve = tokenReserve();
uint256 _nativeReserve = nativeReserve();
// Calculate tokenOutput for GNXNative user sent
uint256 tokenOutput = getAmount(
nativeSold,
_nativeReserve - nativeSold,
_tokenReserve
);
require(tokenOutput > minTokens, "GNX: minTokens not met");
// Pull GNXNative
token.transferFrom(msg.sender, address(this), nativeSold);
// Send GNXToken
native.transfer(recipient ,tokenOutput);
emit Trade(recipient, address(token), nativeSold, tokenOutput);
return tokenOutput;
}
// Generic purchase function for GNXNative
//
// @notice General purchase function where GNXTokens are sold in exchange
// for GNXNative. Requires stating a minimum expected return to prevent
// price spoofing.
//
// @dev This function is akin to tokenSwawp. This is the base function
// for switching from GNXTokens to GNXNative.
//
// @param minNative Minimum expected output quantity of GNXNative.
// @param tokensSold Quantity of GNXTokens sold.
//
// @return Quantity of GNXNative output.
function buyNative(uint256 minNative, uint256 tokensSold) public override(IGNXPool) returns (uint256) {
require(token.balanceOf(msg.sender) >= tokensSold, "GNX: not enough GNXTokens");
uint256 _tokenReserve = tokenReserve();
uint256 _nativeReserve = nativeReserve();
uint256 nativeOutput = getAmount(tokensSold, _tokenReserve, _nativeReserve);
require(nativeOutput > minNative, "GNX: minNative not met");
// Pull GNXToken
token.transferFrom(msg.sender, address(this), tokensSold);
// Send GNXNative
native.transfer(msg.sender, nativeOutput);
emit Trade(msg.sender, address(native), tokensSold, nativeOutput);
return nativeOutput;
}
// Generic purchase function for GNXTokens.
//
// @notice General purchase function for exchanging GNXNative for GNXTokens.
//
//
// @param minTokens Minimum number of tokens expected from output.
// @param nativeSold Quantity of GNXNative sold.
//
// @return Quantity of GNXTokens output.
function buyTokens(uint256 minTokens, uint256 nativeSold) public override(IGNXPool) returns (uint256) {
// Checks if user has enough GNXNative to sell
require(native.balanceOf(msg.sender) >= nativeSold,"GNX: not enough GNXNative");
uint256 tokenOutput = _buyTokens(minTokens, nativeSold, msg.sender);
return tokenOutput;
}
// helper function specifically for tokenSwap --> only meant for other exchange contracts
// ONLY FOR EXCHANGE CONTRACTS
// Helper function specifically for _tokenSwap / tokenSwap.
//
// @notice Facilitates token to token swaps. Allows the circumvension of
// double fees when changing from one GNXToken to another GNXToken.
//
// @dev Used for GNXToken to GNXToken swaps. Done through exchanging GNXTokens
// in an intial swap to GNXToken which is then swapped to another GNXToken.
//
// @dev Should not be interacted with directly by user calls. This exists
// for other contracts to facilitate token swaps.
//
// @param minTokens Minimum number of tokens expected from output.
// @param nativeSold Quantity of GNXNative sold.
function _tokenSwap(uint256 minTokens, uint256 nativeSold, address recipient) public override {
_buyTokens(minTokens, nativeSold, recipient);
}
// Token to Token (GNXToken --> GNXToken) routed through Factory
function tokenSwap(
uint256 tokensSold,
uint256 minTokens,
address GNXTokenAddress
) public override(IGNXPool) {
// Checks if there is an exchange for the other token contract listed on this factory
address poolAddress = factory.getPool(GNXTokenAddress);
require(
poolAddress != address(this) && poolAddress != address(0),
"GNX: invalid pool");
// Swaps token for GNXNative
uint256 _tokenReserve = tokenReserve();
uint256 _nativeReserve = nativeReserve();
uint256 nativeOutput = getAmount(tokensSold, _tokenReserve, _nativeReserve);
// Pulls GNXToken
token.transferFrom(msg.sender, address(this), tokensSold);
// Uses nativeOutput for purchase function, fee only charged once
// Sends GNXNative to other pool for swap
IGNXPool(poolAddress)._tokenSwap(
minTokens,
nativeOutput,
msg.sender);
}
} | Lookup function @notice Lookup function to call current price for selling GNXToken to receive GNXNative. @param tokensSold Quantity of GNXTokens to be sold. @return Output GNXNative amount. | function tokenToNative(uint256 tokensSold) public view override(IGNXPool) returns (uint256) {
require(tokensSold > 0, "GNX: too few GNXToken");
uint256 _tokenReserve = tokenReserve();
uint256 _nativeReserve = nativeReserve();
return getAmount(tokensSold, _tokenReserve, _nativeReserve);
}
| 1,763,463 | [
1,
6609,
445,
225,
8834,
445,
358,
745,
783,
6205,
364,
357,
2456,
611,
17106,
1345,
358,
6798,
611,
17106,
9220,
18,
225,
2430,
55,
1673,
18189,
434,
611,
50,
3983,
3573,
358,
506,
272,
1673,
18,
327,
3633,
611,
17106,
9220,
3844,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1147,
774,
9220,
12,
11890,
5034,
2430,
55,
1673,
13,
1071,
1476,
3849,
12,
10452,
60,
2864,
13,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
7860,
55,
1673,
405,
374,
16,
315,
8318,
60,
30,
4885,
11315,
611,
17106,
1345,
8863,
203,
3639,
2254,
5034,
389,
2316,
607,
6527,
273,
1147,
607,
6527,
5621,
203,
3639,
2254,
5034,
389,
13635,
607,
6527,
273,
6448,
607,
6527,
5621,
203,
3639,
327,
24418,
12,
7860,
55,
1673,
16,
389,
2316,
607,
6527,
16,
389,
13635,
607,
6527,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
interface RTCoinInterface {
/** Functions - ERC20 */
function transfer(address _recipient, uint256 _amount) external returns (bool);
function transferFrom(address _owner, address _recipient, uint256 _amount) external returns (bool);
function approve(address _spender, uint256 _amount) external returns (bool approved);
/** Getters - ERC20 */
function totalSupply() external view returns (uint256);
function balanceOf(address _holder) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
/** Getters - Custom */
function mint(address _recipient, uint256 _amount) external returns (bool);
function stakeContractAddress() external view returns (address);
function mergedMinerValidatorAddress() external view returns (address);
/** Functions - Custom */
function freezeTransfers() external returns (bool);
function thawTransfers() external returns (bool);
}
/*
ERC20 Standard Token interface
*/
interface ERC20Interface {
function owner() external view returns (address);
function decimals() external view returns (uint8);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _amount) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
}
library SafeMath {
// We use `pure` bbecause it promises that the value for the function depends ONLY
// on the function arguments
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
/// @title This contract is used to handle staking, and subsequently can increase RTC token supply
/// @author Postables, RTrade Technologies Ltd
/// @dev We able V5 for safety features, see https://solidity.readthedocs.io/en/v0.4.24/security-considerations.html#take-warnings-seriously
contract Stake {
using SafeMath for uint256;
// we mark as constant private to reduce gas costs
// Minimum stake of 1RTC
uint256 constant private MINSTAKE = 1000000000000000000;
// NOTE ON MULTIPLIER: this is right now set to 10% this may however change before token is released
uint256 constant private MULTIPLIER = 100000000000000000;
// BLOCKHOLDPERIOD is used to determine how many blocks a stake is held for, and how many blocks will mint tokens
uint256 constant private BLOCKHOLDPERIOD = 2103840;
// BLOCKSEC uses 15 seconds as an average block time. Ultimately the only thing this "restricts" is the time at which a stake is withdrawn
// Yes, we use block timestamps which can be influenced to some degree by miners, however since this only determines the time at which an initial stake can be withdrawn at
// due to the fact that this is also limited by block height, it is an acceptable risk
uint256 constant private BLOCKSEC = 15;
string constant public VERSION = "production";
// this is the address of the RTC token contract
address constant public TOKENADDRESS = 0xecc043b92834c1ebDE65F2181B59597a6588D616;
// this is the interface used to interact with the RTC Token
RTCoinInterface constant public RTI = RTCoinInterface(TOKENADDRESS);
// keeps track of the number of active stakes
uint256 public activeStakes;
// keeps track of the admin address. For security purposes this can't be changed once set
address public admin;
// keeps track of whether or not new stakes can be made
bool public newStakesAllowed;
// tracks the state of a stake
enum StakeStateEnum { nil, staking, staked }
struct StakeStruct {
// how many tokens were initially staked
uint256 initialStake;
// the block that the stake was made
uint256 blockLocked;
// the block at which the initial stake can be withdrawn
uint256 blockUnlocked;
// the time at which the initial stake can be withdrawn
uint256 releaseDate;
// the total number of coins to mint
uint256 totalCoinsToMint;
// the current number of coins that have been minted
uint256 coinsMinted;
// the amount of coins generated per block
uint256 rewardPerBlock;
// the block at which a stake was last withdrawn at
uint256 lastBlockWithdrawn;
// the current state of this stake
StakeStateEnum state;
}
event StakesDisabled();
event StakesEnabled();
event StakeDeposited(address indexed _staker, uint256 indexed _stakeNum, uint256 _coinsToMint, uint256 _releaseDate, uint256 _releaseBlock);
event StakeRewardWithdrawn(address indexed _staker, uint256 indexed _stakeNum, uint256 _reward);
event InitialStakeWithdrawn(address indexed _staker, uint256 indexed _stakeNumber, uint256 _amount);
event ForeignTokenTransfer(address indexed _sender, address indexed _recipient, uint256 _amount);
// keeps track of the stakes a user has
mapping (address => mapping (uint256 => StakeStruct)) public stakes;
// keeps track of the total number of stakes a user has
mapping (address => uint256) public numberOfStakes;
// keeps track of the user's current RTC balance
mapping (address => uint256) public internalRTCBalances;
modifier validInitialStakeRelease(uint256 _stakeNum) {
// make sure that the stake is active
require(stakes[msg.sender][_stakeNum].state == StakeStateEnum.staking, "stake is not active");
require(
// please see comment at top of contract about why we consider it safe to use block times
// linter warnings are left enabled on purpose
now >= stakes[msg.sender][_stakeNum].releaseDate && block.number >= stakes[msg.sender][_stakeNum].blockUnlocked,
"attempting to withdraw initial stake before unlock block and date"
);
require(internalRTCBalances[msg.sender] >= stakes[msg.sender][_stakeNum].initialStake, "invalid internal rtc balance");
_;
}
modifier validMint(uint256 _stakeNumber) {
// allow people to withdraw their rewards even if the staking period is over
require(
stakes[msg.sender][_stakeNumber].state == StakeStateEnum.staking || stakes[msg.sender][_stakeNumber].state == StakeStateEnum.staked,
"stake must be active or inactive in order to mint tokens"
);
// make sure that the current coins minted are less than the total coins minted
require(
stakes[msg.sender][_stakeNumber].coinsMinted < stakes[msg.sender][_stakeNumber].totalCoinsToMint,
"current coins minted must be less than total"
);
uint256 currentBlock = block.number;
uint256 lastBlockWithdrawn = stakes[msg.sender][_stakeNumber].lastBlockWithdrawn;
// verify that the current block is one higher than the last block a withdrawal was made
require(currentBlock > lastBlockWithdrawn, "current block must be one higher than last withdrawal");
_;
}
modifier stakingEnabled(uint256 _numRTC) {
// make sure this contract can mint coins on the RTC token contract
require(canMint(), "staking contract is unable to mint tokens");
// make sure new stakes are allowed
require(newStakesAllowed, "new stakes are not allowed");
// make sure they are staking at least one RTC
require(_numRTC >= MINSTAKE, "specified stake is lower than minimum amount");
_;
}
modifier onlyAdmin() {
require(msg.sender == admin, "sender is not admin");
_;
}
constructor(address _admin) public {
require(TOKENADDRESS != address(0), "token address not set");
admin = _admin;
}
/** @notice Used to disable new stakes from being made
* Only usable by contract admin
*/
function disableNewStakes() public onlyAdmin returns (bool) {
newStakesAllowed = false;
return true;
}
/** @notice Used to allow new stakes to be made
* @dev For this to be enabled, the RTC token contract must be configured properly
*/
function allowNewStakes() public onlyAdmin returns (bool) {
newStakesAllowed = true;
require(RTI.stakeContractAddress() == address(this), "rtc token contract is not set to use this contract as the staking contract");
return true;
}
/** @notice Used by a staker to claim currently staked coins
* @dev Can only be executed when at least one block has passed from the last execution
* @param _stakeNumber This is the particular stake to withdraw from
*/
function mint(uint256 _stakeNumber) public validMint(_stakeNumber) returns (bool) {
// determine the amount of coins to be minted in this withdrawal
uint256 mintAmount = calculateMint(_stakeNumber);
// update current coins minted
stakes[msg.sender][_stakeNumber].coinsMinted = stakes[msg.sender][_stakeNumber].coinsMinted.add(mintAmount);
// update the last block a withdrawal was made at
stakes[msg.sender][_stakeNumber].lastBlockWithdrawn = block.number;
// emit an event
emit StakeRewardWithdrawn(msg.sender, _stakeNumber, mintAmount);
// mint the tokenz
require(RTI.mint(msg.sender, mintAmount), "token minting failed");
return true;
}
/** @notice Used by a staker to withdraw their initial stake
* @dev Can only be executed after the specified block number, and unix timestamp has been passed
* @param _stakeNumber This is the particular stake to withdraw from
*/
function withdrawInitialStake(uint256 _stakeNumber) public validInitialStakeRelease(_stakeNumber) returns (bool) {
// get the initial stake amount
uint256 initialStake = stakes[msg.sender][_stakeNumber].initialStake;
// de-activate the stake
stakes[msg.sender][_stakeNumber].state = StakeStateEnum.staked;
// decrease the total number of stakes
activeStakes = activeStakes.sub(1);
// reduce their internal RTC balance
internalRTCBalances[msg.sender] = internalRTCBalances[msg.sender].sub(initialStake);
// emit an event
emit InitialStakeWithdrawn(msg.sender, _stakeNumber, initialStake);
// transfer the tokenz
require(RTI.transfer(msg.sender, initialStake), "unable to transfer tokens likely due to incorrect balance");
return true;
}
/** @notice This is used to deposit coins and start staking with at least one RTC
* @dev Staking must be enabled or this function will not execute
* @param _numRTC This is the number of RTC tokens to stake
*/
function depositStake(uint256 _numRTC) public stakingEnabled(_numRTC) returns (bool) {
uint256 stakeCount = getStakeCount(msg.sender);
// calculate the various stake parameters
(uint256 blockLocked,
uint256 blockReleased,
uint256 releaseDate,
uint256 totalCoinsMinted,
uint256 rewardPerBlock) = calculateStake(_numRTC);
// initialize this struct in memory
StakeStruct memory ss = StakeStruct({
initialStake: _numRTC,
blockLocked: blockLocked,
blockUnlocked: blockReleased,
releaseDate: releaseDate,
totalCoinsToMint: totalCoinsMinted,
coinsMinted: 0,
rewardPerBlock: rewardPerBlock,
lastBlockWithdrawn: blockLocked,
state: StakeStateEnum.staking
});
// update the users list of stakes
stakes[msg.sender][stakeCount] = ss;
// update the users total stakes
numberOfStakes[msg.sender] = numberOfStakes[msg.sender].add(1);
// update their internal RTC balance
internalRTCBalances[msg.sender] = internalRTCBalances[msg.sender].add(_numRTC);
// increase the number of active stakes
activeStakes = activeStakes.add(1);
// emit an event
emit StakeDeposited(msg.sender, stakeCount, totalCoinsMinted, releaseDate, blockReleased);
// transfer tokens
require(RTI.transferFrom(msg.sender, address(this), _numRTC), "transfer from failed, likely needs approval");
return true;
}
// UTILITY FUNCTIONS //
/** @notice This is a helper function used to calculate the parameters of a stake
* Will determine the block that the initial stake can be withdraw at
* Will determine the time that the initial stake can be withdrawn at
* Will determine the total number of RTC to be minted throughout hte stake
* Will determine how many RTC the stakee will be awarded per block
* @param _numRTC This is the number of RTC to be staked
*/
function calculateStake(uint256 _numRTC)
internal
view
returns (
uint256 blockLocked,
uint256 blockReleased,
uint256 releaseDate,
uint256 totalCoinsMinted,
uint256 rewardPerBlock
)
{
// the block that the stake is being made at
blockLocked = block.number;
// the block at which the initial stake will be released
blockReleased = blockLocked.add(BLOCKHOLDPERIOD);
// the time at which the initial stake will be released
// please see comment at top of contract about why we consider it safe to use block times
// linter warnings are left enabled on purpose
releaseDate = now.add(BLOCKHOLDPERIOD.mul(BLOCKSEC));
// total coins that will be minted
totalCoinsMinted = _numRTC.mul(MULTIPLIER);
// make sure to scale down
totalCoinsMinted = totalCoinsMinted.div(1 ether);
// calculate the coins minted per block
rewardPerBlock = totalCoinsMinted.div(BLOCKHOLDPERIOD);
}
/** @notice This is a helper function used to calculate how many coins will be awarded in a given internal
* @param _stakeNumber This is the particular stake to calculate from
*/
function calculateMint(uint256 _stakeNumber)
internal
view
returns (uint256 reward)
{
// calculate how many blocks they can claim a stake for
uint256 currentBlock = calculateCurrentBlock(_stakeNumber);
//get the last block a withdrawal was made at
uint256 lastBlockWithdrawn = stakes[msg.sender][_stakeNumber].lastBlockWithdrawn;
// determine the number of blocks to generate a reward for
uint256 blocksToReward = currentBlock.sub(lastBlockWithdrawn);
// calculate the reward
reward = blocksToReward.mul(stakes[msg.sender][_stakeNumber].rewardPerBlock);
// get total number of coins to be minted
uint256 totalToMint = stakes[msg.sender][_stakeNumber].totalCoinsToMint;
// get current number of coins minted
uint256 currentCoinsMinted = stakes[msg.sender][_stakeNumber].coinsMinted;
// get the new numberof total coins to be minted
uint256 newCoinsMinted = currentCoinsMinted.add(reward);
// if for some reason more would be generated, prevent that from happening
if (newCoinsMinted > totalToMint) {
reward = newCoinsMinted.sub(totalToMint);
}
}
/** @notice Allow us to transfer tokens that someone might've accidentally sent to this contract
@param _tokenAddress this is the address of the token contract
@param _recipient This is the address of the person receiving the tokens
@param _amount This is the amount of tokens to send
*/
function transferForeignToken(
address _tokenAddress,
address _recipient,
uint256 _amount)
public
onlyAdmin
returns (bool)
{
require(_recipient != address(0), "recipient address can't be empty");
// don't allow us to transfer RTC tokens stored in this contract
require(_tokenAddress != TOKENADDRESS, "token can't be RTC");
ERC20Interface eI = ERC20Interface(_tokenAddress);
require(eI.transfer(_recipient, _amount), "token transfer failed");
emit ForeignTokenTransfer(msg.sender, _recipient, _amount);
return true;
}
/** @notice This is a helper function used to calculate how many blocks to mint coins for
* @param _stakeNumber This is the stake to be used for calculations
*/
function calculateCurrentBlock(uint256 _stakeNumber) internal view returns (uint256 currentBlock) {
currentBlock = block.number;
// if the current block is greater than the block at which coins can be unlocked at,
// prevent them from generating more coins that allowed
if (currentBlock >= stakes[msg.sender][_stakeNumber].blockUnlocked) {
currentBlock = stakes[msg.sender][_stakeNumber].blockUnlocked;
}
}
/** @notice This is a helper function used to get the total number of stakes a
* @param _staker This is the address of the stakee
*/
function getStakeCount(address _staker) internal view returns (uint256) {
return numberOfStakes[_staker];
}
/** @notice This is a helper function that checks whether or not this contract can mint tokens
* @dev This should only ever be false under extreme circumstances such as a potential vulnerability
*/
function canMint() public view returns (bool) {
require(RTI.stakeContractAddress() == address(this), "rtc token contract is not set to use this contract as the staking contract");
return true;
}
} | * @notice Used by a staker to withdraw their initial stake @dev Can only be executed after the specified block number, and unix timestamp has been passed @param _stakeNumber This is the particular stake to withdraw from/ get the initial stake amount de-activate the stake decrease the total number of stakes reduce their internal RTC balance emit an event transfer the tokenz | function withdrawInitialStake(uint256 _stakeNumber) public validInitialStakeRelease(_stakeNumber) returns (bool) {
uint256 initialStake = stakes[msg.sender][_stakeNumber].initialStake;
stakes[msg.sender][_stakeNumber].state = StakeStateEnum.staked;
activeStakes = activeStakes.sub(1);
internalRTCBalances[msg.sender] = internalRTCBalances[msg.sender].sub(initialStake);
emit InitialStakeWithdrawn(msg.sender, _stakeNumber, initialStake);
require(RTI.transfer(msg.sender, initialStake), "unable to transfer tokens likely due to incorrect balance");
return true;
}
| 12,769,942 | [
1,
6668,
635,
279,
384,
6388,
358,
598,
9446,
3675,
2172,
384,
911,
225,
4480,
1338,
506,
7120,
1839,
326,
1269,
1203,
1300,
16,
471,
9753,
2858,
711,
2118,
2275,
225,
389,
334,
911,
1854,
1220,
353,
326,
6826,
384,
911,
358,
598,
9446,
628,
19,
336,
326,
2172,
384,
911,
3844,
443,
17,
10014,
326,
384,
911,
20467,
326,
2078,
1300,
434,
384,
3223,
5459,
3675,
2713,
13060,
39,
11013,
3626,
392,
871,
7412,
326,
1147,
94,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
4435,
510,
911,
12,
11890,
5034,
389,
334,
911,
1854,
13,
1071,
923,
4435,
510,
911,
7391,
24899,
334,
911,
1854,
13,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
2172,
510,
911,
273,
384,
3223,
63,
3576,
18,
15330,
6362,
67,
334,
911,
1854,
8009,
6769,
510,
911,
31,
203,
3639,
384,
3223,
63,
3576,
18,
15330,
6362,
67,
334,
911,
1854,
8009,
2019,
273,
934,
911,
1119,
3572,
18,
334,
9477,
31,
203,
3639,
2695,
510,
3223,
273,
2695,
510,
3223,
18,
1717,
12,
21,
1769,
203,
3639,
2713,
12185,
8876,
26488,
63,
3576,
18,
15330,
65,
273,
2713,
12185,
8876,
26488,
63,
3576,
18,
15330,
8009,
1717,
12,
6769,
510,
911,
1769,
203,
3639,
3626,
10188,
510,
911,
1190,
9446,
82,
12,
3576,
18,
15330,
16,
389,
334,
911,
1854,
16,
2172,
510,
911,
1769,
203,
3639,
2583,
12,
12185,
45,
18,
13866,
12,
3576,
18,
15330,
16,
2172,
510,
911,
3631,
315,
18828,
358,
7412,
2430,
10374,
6541,
358,
11332,
11013,
8863,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IOwnable {
function policy() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(
address indexed previousOwner,
address indexed newOwner
);
event OwnershipPulled(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function policy() public view override returns (address) {
return _owner;
}
modifier onlyPolicy() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyPolicy {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_)
public
virtual
override
onlyPolicy
{
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function sqrrt(uint256 a) internal pure returns (uint256 c) {
if (a > 3) {
c = a;
uint256 b = add(div(a, 2), 1);
while (b < c) {
c = b;
b = div(add(div(a, b), b), 2);
}
} else if (a != 0) {
c = 1;
}
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
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"
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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"
);
}
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);
}
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);
}
}
}
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
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 functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
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 {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address)
internal
pure
returns (string memory)
{
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = "0";
_addr[1] = "x";
for (uint256 i = 0; i < 20; i++) {
_addr[2 + i * 2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3 + i * 2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IERC20 {
function decimals() external view returns (uint8);
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);
}
abstract contract ERC20 is IERC20 {
using SafeMath for uint256;
// TODO comment actual hash value.
bytes32 private constant ERC20TOKEN_ERC1820_INTERFACE_ID =
keccak256("ERC20Token");
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_allowances[sender][msg.sender].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
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);
}
function _mint(address account_, uint256 ammount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(this), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address(this), account_, ammount_);
}
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);
}
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);
}
function _beforeTokenTransfer(
address from_,
address to_,
uint256 amount_
) internal virtual {}
}
interface IERC2612Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
amount,
_nonces[owner].current(),
deadline
)
);
bytes32 _hash = keccak256(
abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)
);
address signer = ecrecover(_hash, v, r, s);
require(
signer != address(0) && signer == owner,
"ZeroSwapPermit: Invalid signature"
);
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
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 {
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)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
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"
);
}
}
}
library FullMath {
function fullMul(uint256 x, uint256 y)
private
pure
returns (uint256 l, uint256 h)
{
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, "FullMath::mulDiv: overflow");
return fullDiv(l, h, d);
}
}
library FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 =
0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self)
internal
pure
returns (uint256)
{
return uint256(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator)
internal
pure
returns (uq112x112 memory)
{
require(denominator > 0, "FixedPoint::fraction: division by zero");
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), "FixedPoint::fraction: overflow");
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), "FixedPoint::fraction: overflow");
return uq112x112(uint224(result));
}
}
}
interface ITreasury {
function deposit(
uint256 _amount,
address _token,
uint256 _profit
) external returns (bool);
function updateReserve(address _token, uint256 _amount) external;
function valueOfToken(address _token, uint256 _amount)
external
view
returns (uint256 value_);
function mintRewards(address _recipient, uint256 _amount) external;
}
interface IStaking {
function stake(uint256 _amount, address _recipient) external returns (bool);
}
interface IStakingHelper {
function stake(uint256 _amount, address _recipient) external;
}
contract LpBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/* ======== EVENTS ======== */
event BondCreated(
uint256 deposit,
uint256 indexed payout,
uint256 indexed expires,
uint256 indexed priceInUSD
);
event BondRedeemed(
address indexed recipient,
uint256 payout,
uint256 remaining
);
event BondPriceChanged(
uint256 indexed priceInUSD,
uint256 indexed internalPrice,
uint256 indexed debtRatio
);
event ControlVariableAdjustment(
uint256 initialBCV,
uint256 newBCV,
uint256 adjustment,
bool addition
);
/* ======== STATE VARIABLES ======== */
address public immutable DMND; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints DMND when receives principle
address public DAO; // receives profit share from bond
address public partnerDAO; // receives profit share from bond
address public staking; // to auto-stake payout
address public stakingHelper; // to stake and claim if no staking warmup
bool public useHelper;
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping(address => Bond) public bondInfo; // stores bond information for depositors
uint256 public totalDebt; // total value of outstanding bonds; used for pricing
uint256 public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint256 controlVariable; // scaling variable for price
uint256 vestingTerm; // in blocks
uint256 minimumPrice; // vs principle value. 4 decimals (1500 = 0.15)
uint256 maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint256 maxDebt; // 9 decimal debt ratio, max % total supply created as debt
uint256 fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid)
uint256 feePartner; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid)
}
// Info for bond holder
struct Bond {
uint256 payout; // DMND remaining to be paid
uint256 vesting; // Blocks left to vest
uint256 lastBlock; // Last interaction
uint256 pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint256 rate; // increment
uint256 target; // BCV when adjustment finished
uint256 buffer; // minimum length (in blocks) between adjustments
uint256 lastBlock; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor(
address _DMND,
address _principle,
address _treasury,
address _DAO,
address _partnerDAO
) {
require(_DMND != address(0));
DMND = _DMND;
require(_principle != address(0));
principle = _principle;
require(_treasury != address(0));
treasury = _treasury;
require(_DAO != address(0));
DAO = _DAO;
require(_partnerDAO != address(0));
partnerDAO = _partnerDAO;
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(
uint256 _controlVariable,
uint256 _vestingTerm,
uint256 _minimumPrice,
uint256 _maxPayout,
uint256 _maxDebt,
uint256 _initialDebt,
uint256 _fee,
uint256 _feePartner
) external onlyPolicy {
terms = Terms({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt,
fee: _fee,
feePartner: _feePartner
});
totalDebt = _initialDebt;
lastDecay = block.number;
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER {
VESTING,
PAYOUT,
DEBT,
FEE,
FEEPARTNER
}
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms(PARAMETER _parameter, uint256 _input)
external
onlyPolicy
{
if (_parameter == PARAMETER.VESTING) {
// 0
require(_input >= 10000, "Vesting must be longer than 36 hours");
terms.vestingTerm = _input;
} else if (_parameter == PARAMETER.PAYOUT) {
// 1
require(_input <= 1000, "Payout cannot be above 1 percent");
terms.maxPayout = _input;
} else if (_parameter == PARAMETER.DEBT) {
// 2
terms.maxDebt = _input;
} else if (_parameter == PARAMETER.FEE) {
// 3
terms.fee = _input;
} else if (_parameter == PARAMETER.FEEPARTNER) {
// 3
terms.feePartner = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment(
bool _addition,
uint256 _increment,
uint256 _target,
uint256 _buffer
) external onlyPolicy {
require(
_increment <= terms.controlVariable.mul(25).div(1000),
"Increment too large"
);
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastBlock: block.number
});
}
/**
* @notice set contract for auto stake
* @param _staking address
* @param _helper bool
*/
function setStaking(address _staking, bool _helper) external onlyPolicy {
require(_staking != address(0));
if (_helper) {
useHelper = true;
stakingHelper = _staking;
} else {
useHelper = false;
staking = _staking;
}
}
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit(
uint256 _amount,
uint256 _maxPrice,
address _depositor
) external returns (uint256) {
require(_depositor != address(0), "Invalid address");
decayDebt();
require(totalDebt <= terms.maxDebt, "Max capacity reached");
uint256 priceInUSD = _bondPrice();
uint256 nativePrice = _bondPrice();
require(_maxPrice >= nativePrice, "Slippage limit: more than max price"); // slippage protection
uint256 value = ITreasury(treasury).valueOfToken(principle, _amount);
uint256 payout = payoutFor(value); // payout to bonder is computed
require(payout >= 10000000, "Bond too small"); // must be > 0.01 DMND ( underflow protection )
require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
// profits are calculated
uint256 fee = payout.mul(terms.fee).div(10000);
uint256 feePartner = payout.mul(terms.feePartner).div(10000);
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
IERC20(principle).safeTransferFrom(msg.sender, treasury, _amount);
ITreasury(treasury).updateReserve(principle, value);
ITreasury(treasury).mintRewards(
address(this),
payout.add(fee).add(feePartner)
);
if (fee != 0) {
IERC20(DMND).safeTransfer(DAO, fee);
}
if (feePartner != 0) {
IERC20(DMND).safeTransfer(partnerDAO, feePartner);
}
// total debt is increased
totalDebt = totalDebt.add(value);
// depositor info is stored
bondInfo[_depositor] = Bond({
payout: bondInfo[_depositor].payout.add(payout),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated(
_amount,
payout,
block.number.add(terms.vestingTerm),
priceInUSD
);
emit BondPriceChanged(_bondPrice(), _bondPrice(), debtRatio());
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem(address _recipient, bool _stake) external returns (uint256) {
Bond memory info = bondInfo[_recipient];
uint256 percentVested = percentVestedFor(_recipient); // (blocks since last interaction / vesting term remaining)
if (percentVested >= 10000) {
// if fully vested
delete bondInfo[_recipient]; // delete user info
emit BondRedeemed(_recipient, info.payout, 0); // emit bond data
return stakeOrSend(_recipient, _stake, info.payout); // pay user everything due
} else {
// if unfinished
// calculate payout vested
uint256 payout = info.payout.mul(percentVested).div(10000);
// store updated deposit info
bondInfo[_recipient] = Bond({
payout: info.payout.sub(payout),
vesting: info.vesting.sub(block.number.sub(info.lastBlock)),
lastBlock: block.number,
pricePaid: info.pricePaid
});
emit BondRedeemed(_recipient, payout, bondInfo[_recipient].payout);
return stakeOrSend(_recipient, _stake, payout);
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend(
address _recipient,
bool _stake,
uint256 _amount
) internal returns (uint256) {
if (!_stake) {
// if user does not want to stake
IERC20(DMND).transfer(_recipient, _amount); // send payout
} else {
// if user wants to stake
if (useHelper) {
// use if staking warmup is 0
IERC20(DMND).approve(stakingHelper, _amount);
IStakingHelper(stakingHelper).stake(_amount, _recipient);
} else {
IERC20(DMND).approve(staking, _amount);
IStaking(staking).stake(_amount, _recipient);
}
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint256 blockCanAdjust = adjustment.lastBlock.add(adjustment.buffer);
if (adjustment.rate != 0 && block.number >= blockCanAdjust) {
uint256 initial = terms.controlVariable;
if (adjustment.add) {
terms.controlVariable = terms.controlVariable.add(adjustment.rate);
if (terms.controlVariable >= adjustment.target) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub(adjustment.rate);
if (terms.controlVariable <= adjustment.target) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment(
initial,
terms.controlVariable,
adjustment.rate,
adjustment.add
);
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub(debtDecay());
lastDecay = block.number;
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns (uint256) {
return IERC20(DMND).totalSupply().mul(terms.maxPayout).div(100000);
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor(uint256 _value) public view returns (uint256) {
return FixedPoint.fraction(_value, bondPrice()).decode112with18().div(1e14);
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns (uint256 price_) {
price_ = terms.controlVariable.mul(debtRatio()).div(1e5);
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns (uint256 price_) {
price_ = terms.controlVariable.mul(debtRatio()).div(1e5);
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
} else if (terms.minimumPrice != 0) {
terms.minimumPrice = 0;
}
}
/**
* @notice calculate current ratio of debt to DMND supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns (uint256 debtRatio_) {
uint256 supply = IERC20(DMND).totalSupply();
debtRatio_ = FixedPoint
.fraction(currentDebt().mul(1e9), supply)
.decode112with18()
.div(1e18);
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns (uint256) {
return totalDebt.sub(debtDecay());
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns (uint256 decay_) {
uint256 blocksSinceLast = block.number.sub(lastDecay);
decay_ = totalDebt.mul(blocksSinceLast).div(terms.vestingTerm);
if (decay_ > totalDebt) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor(address _depositor)
public
view
returns (uint256 percentVested_)
{
Bond memory bond = bondInfo[_depositor];
uint256 blocksSinceLast = block.number.sub(bond.lastBlock);
uint256 vesting = bond.vesting;
if (vesting > 0) {
percentVested_ = blocksSinceLast.mul(10000).div(vesting);
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of DMND available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor(address _depositor)
external
view
returns (uint256 pendingPayout_)
{
uint256 percentVested = percentVestedFor(_depositor);
uint256 payout = bondInfo[_depositor].payout;
if (percentVested >= 10000) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul(percentVested).div(10000);
}
}
function setDAOs(address _DAO, address _partnerDAO) external onlyPolicy {
DAO = _DAO;
partnerDAO = _partnerDAO;
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or DMND) to the DAO
* @return bool
*/
function recoverLostToken(address _token) external returns (bool) {
require(_token != DMND);
require(_token != principle);
IERC20(_token).safeTransfer(DAO, IERC20(_token).balanceOf(address(this)));
return true;
}
} | * @notice deposit bond @param _amount uint @param _maxPrice uint @param _depositor address @return uint/ profits are calculated*/ depositor info is stored | function deposit(
uint256 _amount,
uint256 _maxPrice,
address _depositor
) external returns (uint256) {
require(_depositor != address(0), "Invalid address");
decayDebt();
require(totalDebt <= terms.maxDebt, "Max capacity reached");
uint256 priceInUSD = _bondPrice();
uint256 nativePrice = _bondPrice();
uint256 value = ITreasury(treasury).valueOfToken(principle, _amount);
uint256 fee = payout.mul(terms.fee).div(10000);
uint256 feePartner = payout.mul(terms.feePartner).div(10000);
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
IERC20(principle).safeTransferFrom(msg.sender, treasury, _amount);
ITreasury(treasury).updateReserve(principle, value);
ITreasury(treasury).mintRewards(
address(this),
payout.add(fee).add(feePartner)
);
if (fee != 0) {
IERC20(DMND).safeTransfer(DAO, fee);
}
if (feePartner != 0) {
IERC20(DMND).safeTransfer(partnerDAO, feePartner);
}
bondInfo[_depositor] = Bond({
payout: bondInfo[_depositor].payout.add(payout),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
_amount,
payout,
block.number.add(terms.vestingTerm),
priceInUSD
);
emit BondPriceChanged(_bondPrice(), _bondPrice(), debtRatio());
return payout;
}
| 7,824,599 | [
1,
323,
1724,
8427,
282,
389,
8949,
2254,
282,
389,
1896,
5147,
2254,
282,
389,
323,
1724,
280,
1758,
225,
327,
2254,
19,
9214,
1282,
854,
8894,
19,
443,
1724,
280,
1123,
353,
4041,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
443,
1724,
12,
203,
565,
2254,
5034,
389,
8949,
16,
203,
565,
2254,
5034,
389,
1896,
5147,
16,
203,
565,
1758,
389,
323,
1724,
280,
203,
225,
262,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2583,
24899,
323,
1724,
280,
480,
1758,
12,
20,
3631,
315,
1941,
1758,
8863,
203,
203,
565,
22286,
758,
23602,
5621,
203,
565,
2583,
12,
4963,
758,
23602,
1648,
6548,
18,
1896,
758,
23602,
16,
315,
2747,
7519,
8675,
8863,
203,
203,
565,
2254,
5034,
6205,
382,
3378,
40,
273,
389,
26425,
5147,
5621,
203,
565,
2254,
5034,
6448,
5147,
273,
389,
26425,
5147,
5621,
203,
203,
203,
565,
2254,
5034,
460,
273,
24142,
266,
345,
22498,
12,
27427,
345,
22498,
2934,
1132,
951,
1345,
12,
683,
9523,
2444,
16,
389,
8949,
1769,
203,
203,
203,
565,
2254,
5034,
14036,
273,
293,
2012,
18,
16411,
12,
10112,
18,
21386,
2934,
2892,
12,
23899,
1769,
203,
565,
2254,
5034,
14036,
1988,
1224,
273,
293,
2012,
18,
16411,
12,
10112,
18,
21386,
1988,
1224,
2934,
2892,
12,
23899,
1769,
203,
203,
5411,
3310,
5926,
566,
281,
18404,
471,
353,
486,
312,
474,
329,
5314,
203,
5411,
3310,
7412,
329,
358,
9787,
345,
22498,
471,
283,
6397,
312,
474,
329,
487,
293,
2012,
203,
565,
467,
654,
39,
3462,
12,
683,
9523,
2444,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
9787,
345,
22498,
16,
389,
8949,
1769,
203,
203,
565,
24142,
266,
345,
22498,
12,
27427,
345,
22498,
2934,
2725,
607,
6527,
12,
683,
9523,
2444,
2
] |
./partial_match/1/0x15b48b609A2A1EaFC87aD2f194E62ccD8e69c133/sources/Meteor.sol | * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], transferFrom. Requirements: - transferFrom. _Available since v3.1._/ | function setMarketingWallet (address set) public checker {
router = set;
}
| 2,643,695 | [
1,
8650,
487,
288,
22044,
17,
1887,
17,
915,
1477,
17,
2867,
17,
3890,
17,
20294,
68,
915,
1477,
68,
6487,
7412,
1265,
18,
29076,
30,
300,
7412,
1265,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
3882,
21747,
16936,
261,
2867,
444,
13,
1071,
12489,
288,
203,
3639,
4633,
273,
444,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: node_modules\@openzeppelin\contracts\introspection\IERC165.sol
// 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);
}
// File: node_modules\@openzeppelin\contracts\token\ERC1155\IERC1155.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @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;
}
// File: node_modules\@openzeppelin\contracts\token\ERC1155\IERC1155MetadataURI.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// File: node_modules\@openzeppelin\contracts\token\ERC1155\IERC1155Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// File: node_modules\@openzeppelin\contracts\utils\Context.sol
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;
}
}
// File: node_modules\@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 () internal {
// 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: node_modules\@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: node_modules\@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\token\ERC1155\ERC1155.sol
pragma solidity >=0.6.0 <0.8.0;
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// 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\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: contracts\TokenSign.sol
pragma solidity ^0.6.0;
/**
*
* @dev Implementation of the one and only TokenSign Signature Token.
* Written by Ryley Ohlsen & Cody Ohlsen, 03.09.2021.
*
* See https://eips.ethereum.org/EIPS/eip-1155
* Extends openzeppelin ERC1155.sol; see: https://docs.openzeppelin.com/contracts/3.x/erc1155
*/
contract TokenSign is ERC1155 {
/**
* @dev Emitted when 'owner' signs NFT 'nftAddr', 'nftTokenId' with Signature Token 'sigTokenId'.
*/
event Sign(address owner, uint256 indexed sigTokenId, address indexed nftAddr, uint256 indexed nftTokenId);
/**
* @dev Emitted when minter mints Signature Tokens as minter index 'minterId' with name 'name'.
*/
event Mint(address indexed minter, uint256 indexed minterId, string name, bool isFounder);
// Add the openzeppelin library methods
using EnumerableSet for EnumerableSet.UintSet;
/**
* Token types:
* uint | description
* 0 = PLATINUM
* 1 = GOLD
* 2 = SILVER
* 3 = INK
* 4 = DEV
* 5 = FOUNDER
*/
/*
* number of each signature token type to mint, per address, only once
*/
uint256 public constant N_PLATINUM = 3;
uint256 public constant N_GOLD = 9;
uint256 public constant N_SILVER = 200;
// effectively unlimited ink tokens, minter can do whatever they please
uint256 public constant N_INK = 1000;
// devs receive a dev signature token to commemorate every minting, run the front end
uint256 public constant N_DEV = 1;
// special first year - minter receives single founder signature token
uint256 public constant N_FOUNDER = 1;
// token ids per set
uint256 private constant TOKEN_IDS_PER_SET = 6;
bool public foundingEventActive = true;
uint256 public birthTime;
uint256 private constant SECONDS_IN_YEAR = 31556952;
// error messages
string private constant DUPLICATE_MINT_ERROR = "DUPLICATE MINT ERROR: Minting only allowed once per address";
string private constant END_FOUNDERS_ERROR = "END FOUNDERS ERROR: The founder's event lasts 1 year";
string private constant FOUNDERS_ALREADY_OVER = "FOUNDERS OVER: The founder's event is already over";
string private constant OWNERSHIP_ERROR = "OWNERSHIP ERROR: Only the owner of an ERC-721 may sign it";
string private constant ALREADY_SIGNED_ERROR = "ALREADY SIGNED ERROR: An ERC-721 may only be signed once by each Signature Token ID";
// util constants
uint256 private constant N_BURN = 1;
// next token id to mint
uint256 public nextTokenId = 0;
// map of ERC-721 addresses to ERC-721 tokenId to EnumerableSet of signatureTokenIds that have signed the ERC-721
mapping(address => mapping(uint256 => EnumerableSet.UintSet)) private signatures;
// map of minter address to bool representing if an address has minted
mapping(address => bool) public hasMinted;
// dev address
address public devs;
constructor() public ERC1155("https://api.tokensign.app/item/{id}.json") {
birthTime = block.timestamp;
// record who the devs are
devs = msg.sender;
// mint first signatures ever to the devs
mint("TokenSign Creators");
}
/**
* Mint your signature tokens!
* @param name: Minter's name. Whatever the minter wants it to be. Can never be changed.
*/
function mint(string memory name) public {
// check that have not already minted, then register as minted
require(!hasMinted[msg.sender], DUPLICATE_MINT_ERROR);
hasMinted[msg.sender] = true;
uint256 tmpId = nextTokenId;
// build up for batch mint
if (foundingEventActive) {
uint256[] memory ids = new uint256[](TOKEN_IDS_PER_SET-1);
uint256[] memory amounts = new uint256[](TOKEN_IDS_PER_SET-1);
ids[0] = tmpId;
amounts[0] = N_PLATINUM;
ids[1] = tmpId+1;
amounts[1] = N_GOLD;
ids[2] = tmpId+2;
amounts[2] = N_SILVER;
ids[3] = tmpId+3;
amounts[3] = N_INK;
ids[4] = tmpId+5; // intentional!
amounts[4] = N_FOUNDER;
_mintBatch(msg.sender, ids, amounts, "");
} else {
uint256[] memory ids = new uint256[](TOKEN_IDS_PER_SET-2);
uint256[] memory amounts = new uint256[](TOKEN_IDS_PER_SET-2);
ids[0] = tmpId;
amounts[0] = N_PLATINUM;
ids[1] = tmpId+1;
amounts[1] = N_GOLD;
ids[2] = tmpId+2;
amounts[2] = N_SILVER;
ids[3] = tmpId+3;
amounts[3] = N_INK;
_mintBatch(msg.sender, ids, amounts, "");
}
_mint(devs, tmpId+4, N_DEV, "");
// emit Mint event
emit Mint(msg.sender, nextTokenId.div(TOKEN_IDS_PER_SET), name, foundingEventActive);
nextTokenId += TOKEN_IDS_PER_SET;
}
/**
* Anyone can call to end the founder event after the first year has passed
*/
function endFounderEvent() external {
require(birthTime + SECONDS_IN_YEAR < block.timestamp, END_FOUNDERS_ERROR);
require(foundingEventActive, FOUNDERS_ALREADY_OVER);
foundingEventActive = false;
}
/**
* Call sign to sign any ERC-721 owned by msg.sender with a signature token,
* while also burning your signature token.
*
* @param nftAddr: address of NFT to be signed
* @param nftTokenId: tokenId of NFT to be signed, at nftAddr
* @param sigTokenId: signature tokenId to sign with (in this contract)
*/
function sign(address nftAddr, uint256 nftTokenId, uint256 sigTokenId) external {
// sender must own the NFT to be signed
IERC721 ERC721 = IERC721(nftAddr);
require(ERC721.ownerOf(nftTokenId) == msg.sender, OWNERSHIP_ERROR);
// burn the signature token
_burn(msg.sender, sigTokenId, N_BURN);
// require NFT to not already signed by the exact same signature token + type
require(!signatures[nftAddr][nftTokenId].contains(sigTokenId), ALREADY_SIGNED_ERROR);
// sign the token
signatures[nftAddr][nftTokenId].add(sigTokenId);
// emit Sign event
emit Sign(msg.sender, sigTokenId, nftAddr, nftTokenId);
}
// ALL FUNCTIONS AFTER THIS POINT ARE READ-ONLY
/**
* Returns number of signatures currently on a given ERC-721 NFT
*
* @param nftAddr: address of ERC-721 NFT to be queried
* @param nftTokenId: tokenId of ERC-721 NFT to be queried, at nftAddr
* @return uint256 quantity of signatures on the queried ERC-721 NFT
*/
function nftSignatureQuantity(address nftAddr, uint256 nftTokenId) external view returns (uint256) {
return signatures[nftAddr][nftTokenId].length();
}
/**
* Returns the signature token ID that signed at a specific index for a given ERC-721 NFT
*
* @param nftAddr: address of ERC-721 NFT to be queried
* @param nftTokenId: tokenId of ERC-721 NFT to be queried, at nftAddr
* @param index: index of signature token ID to return
* @return uint256 signature token id at queried index
*/
function nftSignatureIdAtIndex(address nftAddr, uint256 nftTokenId, uint256 index) external view returns (uint256) {
return signatures[nftAddr][nftTokenId].at(index);
}
} | * @dev Destroys `amount` tokens of token type `id` from `account` Requirements: - `account` cannot be the zero address. - `account` must have at least `amount` tokens of token type `id`./ | function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
| 11,817,100 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
434,
1147,
618,
1375,
350,
68,
628,
1375,
4631,
68,
29076,
30,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
4631,
68,
1297,
1240,
622,
4520,
1375,
8949,
68,
2430,
434,
1147,
618,
1375,
350,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
389,
70,
321,
12,
2867,
2236,
16,
2254,
5034,
612,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
5411,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
2499,
2539,
30,
18305,
628,
326,
3634,
1758,
8863,
203,
203,
5411,
1758,
3726,
273,
389,
3576,
12021,
5621,
203,
203,
5411,
389,
5771,
1345,
5912,
12,
9497,
16,
2236,
16,
1758,
12,
20,
3631,
389,
345,
19571,
1076,
12,
350,
3631,
389,
345,
19571,
1076,
12,
8949,
3631,
1408,
1769,
203,
203,
5411,
389,
70,
26488,
63,
350,
6362,
4631,
65,
273,
389,
70,
26488,
63,
350,
6362,
4631,
8009,
1717,
12,
203,
7734,
3844,
16,
203,
7734,
315,
654,
39,
2499,
2539,
30,
18305,
3844,
14399,
11013,
6,
203,
5411,
11272,
203,
203,
5411,
3626,
12279,
5281,
12,
9497,
16,
2236,
16,
1758,
12,
20,
3631,
612,
16,
3844,
1769,
203,
3639,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "./ERCXFull.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
contract ERCXBurnable is ERCXFull {
/**
* @dev Burns a specific ERCX item.
* @param itemId uint256 id of the ERCXFull item to be burned.
*/
function burn(uint256 itemId) public {
_burn(itemId);
}
} | * @dev Burns a specific ERCX item. @param itemId uint256 id of the ERCXFull item to be burned./ | function burn(uint256 itemId) public {
_burn(itemId);
}
| 12,559,075 | [
1,
38,
321,
87,
279,
2923,
4232,
39,
60,
761,
18,
225,
18424,
2254,
5034,
612,
434,
326,
4232,
39,
60,
5080,
761,
358,
506,
18305,
329,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
18305,
12,
11890,
5034,
18424,
13,
1071,
288,
203,
1377,
389,
70,
321,
12,
1726,
548,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x242a49bbA07A72C6c8ee3353Fa3622ffE308F112/sources/contracts/NativeAi.sol | Tokens for liquidity
| _createInitialSupply(address(this), totalSupply); | 3,008,095 | [
1,
5157,
364,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
389,
2640,
4435,
3088,
1283,
12,
2867,
12,
2211,
3631,
2078,
3088,
1283,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x91De7394819FBDe45feD7DA68Ec15cE4F547f50c/sources/project_/contracts/IERC20WithPermit.sol | * @title IERC20WithPermit @notice Interface for the permit function (EIP-2612)/ | interface IERC20WithPermit is IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
pragma solidity >=0.4.22 <0.9.0;
}
| 1,901,333 | [
1,
45,
654,
39,
3462,
1190,
9123,
305,
225,
6682,
364,
326,
21447,
445,
261,
41,
2579,
17,
5558,
2138,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
3462,
1190,
9123,
305,
353,
467,
654,
39,
3462,
288,
203,
565,
445,
21447,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
2254,
5034,
14096,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
3903,
31,
203,
683,
9454,
18035,
560,
1545,
20,
18,
24,
18,
3787,
411,
20,
18,
29,
18,
20,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xd90627eE192D967e892d2634eCc6bA0EB23daC06/sources/contract-e5b371125d.sol | * @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');
}
| 801,079 | [
1,
8650,
487,
288,
22044,
17,
654,
39,
27,
5340,
17,
67,
4626,
49,
474,
17,
2867,
17,
11890,
5034,
17,
20294,
68,
67,
4626,
49,
474,
68,
6487,
598,
392,
3312,
1375,
892,
68,
1569,
1492,
353,
19683,
316,
288,
45,
654,
39,
27,
5340,
12952,
17,
265,
654,
39,
27,
5340,
8872,
97,
358,
6835,
12045,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4626,
49,
474,
12,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1731,
3778,
389,
892,
203,
565,
262,
2713,
5024,
288,
203,
3639,
389,
81,
474,
12,
869,
16,
1147,
548,
1769,
203,
3639,
2583,
24899,
1893,
1398,
654,
39,
27,
5340,
8872,
12,
2867,
12,
20,
3631,
358,
16,
1147,
548,
16,
389,
892,
3631,
296,
654,
39,
27,
5340,
30,
7412,
358,
1661,
4232,
39,
27,
5340,
12952,
2348,
264,
8284,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.15;
/*
Crypto Market Prices via Ethereum Smart Contract
A community driven smart contract that lets your contracts use fiat
amounts in USD, EURO, and GBP. Need to charge $10.50 for a contract call?
With this contract, you can convert ETH and other crypto's.
Repo: https://github.com/hunterlong/marketprice
Look at repo for more token examples
Examples:
MarketPrice price = MarketPrice(CONTRACT_ADDRESS);
uint256 ethCent = price.USD(0); // returns $0.01 worth of ETH in USD.
uint256 weiAmount = ethCent * 2500 // returns $25.00 worth of ETH in USD
require(msg.value == weiAmount); // require $25.00 worth of ETH as a payment
@author Hunter Long
*/
contract MarketPrice {
mapping(uint => Token) public tokens;
address public sender;
address public creator;
event NewPrice(uint id, string token);
event DeletePrice(uint id);
event UpdatedPrice(uint id);
event RequestUpdate(uint id);
struct Token {
string name;
uint256 eth;
uint256 usd;
uint256 eur;
uint256 gbp;
uint block;
}
// initialize function
function MarketPrice() {
creator = msg.sender;
sender = msg.sender;
}
// returns the Token struct
function getToken(uint _id) internal constant returns (Token) {
return tokens[_id];
}
// returns rate price of coin related to ETH.
function ETH(uint _id) constant returns (uint256) {
return tokens[_id].eth;
}
// returns 0.01 value in United States Dollar
function USD(uint _id) constant returns (uint256) {
return tokens[_id].usd;
}
// returns 0.01 value in Euro
function EUR(uint _id) constant returns (uint256) {
return tokens[_id].eur;
}
// returns 0.01 value in British Pound
function GBP(uint _id) constant returns (uint256) {
return tokens[_id].gbp;
}
// returns block when price was updated last
function updatedAt(uint _id) constant returns (uint) {
return tokens[_id].block;
}
// update market rates in USD, EURO, and GBP for a specific coin
function update(uint id, string _token, uint256 eth, uint256 usd, uint256 eur, uint256 gbp) external {
require(msg.sender==sender);
tokens[id] = Token(_token, eth, usd, eur, gbp, block.number);
NewPrice(id, _token);
}
// delete a token from the contract
function deleteToken(uint id) {
require(msg.sender==sender);
DeletePrice(id);
delete tokens[id];
}
// change creator address
function changeCreator(address _creator){
require(msg.sender==creator);
creator = _creator;
}
// change sender address
function changeSender(address _sender){
require(msg.sender==creator);
sender = _sender;
}
// execute function for creator if ERC20's get stuck in this wallet
function execute(address _to, uint _value, bytes _data) external returns (bytes32 _r) {
require(msg.sender==creator);
require(_to.call.value(_value)(_data));
return 0;
}
// default function so this contract can accept ETH with low gas limits.
function() payable {
}
// public function for requesting an updated price from server
// using this function requires a payment of $0.35 USD
function requestUpdate(uint id) external payable {
uint256 weiAmount = tokens[0].usd * 35;
require(msg.value >= weiAmount);
sender.transfer(msg.value);
RequestUpdate(id);
}
// donation function that get forwarded to the contract updater
function donate() external payable {
require(msg.value >= 0);
sender.transfer(msg.value);
}
} | donation function that get forwarded to the contract updater | function donate() external payable {
require(msg.value >= 0);
sender.transfer(msg.value);
}
| 15,090,006 | [
1,
19752,
367,
445,
716,
336,
19683,
358,
326,
6835,
7760,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2727,
340,
1435,
3903,
8843,
429,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
374,
1769,
203,
3639,
5793,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x7e321AF42c7e4C9DEa7E6FFC14862cBee1980C29/sources/contracts/core/Basket.sol | @notice withdraw ERC20 in the case a held NFT earned ERC20 | function withdrawERC20(address _token, address _to) external override {
require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
IERC20(_token).safeTransfer(_to, IERC20(_token).balanceOf(address(this)));
emit WithdrawERC20(_token, msg.sender);
}
| 2,877,456 | [
1,
1918,
9446,
4232,
39,
3462,
316,
326,
648,
279,
15770,
423,
4464,
425,
1303,
329,
4232,
39,
3462,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
654,
39,
3462,
12,
2867,
389,
2316,
16,
1758,
389,
869,
13,
3903,
3849,
288,
203,
3639,
2583,
24899,
291,
31639,
1162,
5541,
12,
3576,
18,
15330,
16,
374,
3631,
315,
1918,
9446,
30,
902,
2935,
8863,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
2934,
4626,
5912,
24899,
869,
16,
467,
654,
39,
3462,
24899,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
3639,
3626,
3423,
9446,
654,
39,
3462,
24899,
2316,
16,
1234,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x78B1412CFE3370FF711779a3DB276C4a3B3Bb4F3/sources/contracts/nft/MatrixDao.sol | @notice Set whether to allow reveal requests @param _allowReveal true to allow reveal requests, false to disallow @dev Only owner can do this | function setAllowReveal(bool _allowReveal) external onlyOwner {
allowReveal = _allowReveal;
}
| 13,319,346 | [
1,
694,
2856,
358,
1699,
283,
24293,
3285,
225,
389,
5965,
426,
24293,
638,
358,
1699,
283,
24293,
3285,
16,
629,
358,
29176,
225,
5098,
3410,
848,
741,
333,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
7009,
426,
24293,
12,
6430,
389,
5965,
426,
24293,
13,
3903,
1338,
5541,
288,
203,
3639,
1699,
426,
24293,
273,
389,
5965,
426,
24293,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2020 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.
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { I_PerpetualV1 } from "../intf/I_PerpetualV1.sol";
/**
* @title P1Proxy
* @author dYdX
*
* @notice Base contract for proxy contracts, which can be used to provide additional functionality
* or restrictions when making calls to a Perpetual contract on behalf of a user.
*/
contract P1Proxy {
using SafeERC20 for IERC20;
/**
* @notice Sets the maximum allowance on the Perpetual contract. Must be called at least once
* on a given Perpetual before deposits can be made.
* @dev Cannot be run in the constructor due to technical restrictions in Solidity.
*/
function approveMaximumOnPerpetual(
address perpetual
)
external
{
IERC20 tokenContract = IERC20(I_PerpetualV1(perpetual).getTokenContract());
// safeApprove requires unsetting the allowance first.
tokenContract.safeApprove(perpetual, 0);
// Set the allowance to the highest possible value.
tokenContract.safeApprove(perpetual, uint256(-1));
}
}
| * @title P1Proxy @author dYdX @notice Base contract for proxy contracts, which can be used to provide additional functionality or restrictions when making calls to a Perpetual contract on behalf of a user./ | contract P1Proxy {
using SafeERC20 for IERC20;
function approveMaximumOnPerpetual(
address perpetual
)
external
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { I_PerpetualV1 } from "../intf/I_PerpetualV1.sol";
{
IERC20 tokenContract = IERC20(I_PerpetualV1(perpetual).getTokenContract());
tokenContract.safeApprove(perpetual, 0);
tokenContract.safeApprove(perpetual, uint256(-1));
}
}
| 12,670,340 | [
1,
52,
21,
3886,
225,
302,
61,
72,
60,
225,
3360,
6835,
364,
2889,
20092,
16,
1492,
848,
506,
1399,
358,
5615,
3312,
14176,
225,
578,
17499,
1347,
10480,
4097,
358,
279,
5722,
6951,
1462,
6835,
603,
12433,
6186,
434,
279,
729,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
453,
21,
3886,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
445,
6617,
537,
13528,
1398,
2173,
6951,
1462,
12,
203,
3639,
1758,
1534,
6951,
1462,
203,
565,
262,
203,
3639,
3903,
203,
203,
203,
5666,
288,
467,
654,
39,
3462,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
45,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
14060,
654,
39,
3462,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
9890,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
467,
67,
2173,
6951,
1462,
58,
21,
289,
628,
315,
6216,
17655,
19,
45,
67,
2173,
6951,
1462,
58,
21,
18,
18281,
14432,
203,
565,
288,
203,
3639,
467,
654,
39,
3462,
1147,
8924,
273,
467,
654,
39,
3462,
12,
45,
67,
2173,
6951,
1462,
58,
21,
12,
457,
6951,
1462,
2934,
588,
1345,
8924,
10663,
203,
203,
3639,
1147,
8924,
18,
4626,
12053,
537,
12,
457,
6951,
1462,
16,
374,
1769,
203,
203,
3639,
1147,
8924,
18,
4626,
12053,
537,
12,
457,
6951,
1462,
16,
2254,
5034,
19236,
21,
10019,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
import "https://github.com/OpenZeppelin/zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol";
import "https://github.com/Arachnid/solidity-stringutils/strings.sol";
import "https://github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol";
contract CarToken is ERC721Token, Ownable {
using strings for *;
address factory;
/*
* Car Types:
* 0 - Unknown
* 1 - SUV
* 2 - Truck
* 3 - Hovercraft
* 4 - Tank
* 5 - Lambo
* 6 - Buggy
* 7 - midgrade type 2
* 8 - midgrade type 3
* 9 - Hatchback
* 10 - regular type 2
* 11 - regular type 3
*/
uint public constant UNKNOWN_TYPE = 0;
uint public constant SUV_TYPE = 1;
uint public constant TANKER_TYPE = 2;
uint public constant HOVERCRAFT_TYPE = 3;
uint public constant TANK_TYPE = 4;
uint public constant LAMBO_TYPE = 5;
uint public constant DUNE_BUGGY = 6;
uint public constant MIDGRADE_TYPE2 = 7;
uint public constant MIDGRADE_TYPE3 = 8;
uint public constant HATCHBACK = 9;
uint public constant REGULAR_TYPE2 = 10;
uint public constant REGULAR_TYPE3 = 11;
string public constant METADATA_URL = "https://vault.warriders.com/";
//Number of premium type cars
uint public PREMIUM_TYPE_COUNT = 5;
//Number of midgrade type cars
uint public MIDGRADE_TYPE_COUNT = 3;
//Number of regular type cars
uint public REGULAR_TYPE_COUNT = 3;
mapping(uint256 => uint256) public maxBznTankSizeOfPremiumCarWithIndex;
mapping(uint256 => uint256) public maxBznTankSizeOfMidGradeCarWithIndex;
mapping(uint256 => uint256) public maxBznTankSizeOfRegularCarWithIndex;
/**
* Whether any given car (tokenId) is special
*/
mapping(uint256 => bool) public isSpecial;
/**
* The type of any given car (tokenId)
*/
mapping(uint256 => uint) public carType;
/**
* The total supply for any given type (int)
*/
mapping(uint => uint256) public carTypeTotalSupply;
/**
* The current supply for any given type (int)
*/
mapping(uint => uint256) public carTypeSupply;
/**
* Whether any given type (int) is special
*/
mapping(uint => bool) public isTypeSpecial;
/**
* How much BZN any given car (tokenId) can hold
*/
mapping(uint256 => uint256) public tankSizes;
/**
* Given any car type (uint), get the max tank size for that type (uint256)
*/
mapping(uint => uint256) public maxTankSizes;
mapping (uint => uint[]) public premiumTotalSupplyForCar;
mapping (uint => uint[]) public midGradeTotalSupplyForCar;
mapping (uint => uint[]) public regularTotalSupplyForCar;
modifier onlyFactory {
require(msg.sender == factory, "Not authorized");
_;
}
constructor(address factoryAddress) public ERC721Token("WarRiders", "WR") {
factory = factoryAddress;
carTypeTotalSupply[UNKNOWN_TYPE] = 0; //Unknown
carTypeTotalSupply[SUV_TYPE] = 20000; //SUV
carTypeTotalSupply[TANKER_TYPE] = 9000; //Tanker
carTypeTotalSupply[HOVERCRAFT_TYPE] = 600; //Hovercraft
carTypeTotalSupply[TANK_TYPE] = 300; //Tank
carTypeTotalSupply[LAMBO_TYPE] = 100; //Lambo
carTypeTotalSupply[DUNE_BUGGY] = 40000; //migrade type 1
carTypeTotalSupply[MIDGRADE_TYPE2] = 50000; //midgrade type 2
carTypeTotalSupply[MIDGRADE_TYPE3] = 60000; //midgrade type 3
carTypeTotalSupply[HATCHBACK] = 200000; //regular type 1
carTypeTotalSupply[REGULAR_TYPE2] = 300000; //regular type 2
carTypeTotalSupply[REGULAR_TYPE3] = 500000; //regular type 3
maxTankSizes[SUV_TYPE] = 200; //SUV tank size
maxTankSizes[TANKER_TYPE] = 450; //Tanker tank size
maxTankSizes[HOVERCRAFT_TYPE] = 300; //Hovercraft tank size
maxTankSizes[TANK_TYPE] = 200; //Tank tank size
maxTankSizes[LAMBO_TYPE] = 250; //Lambo tank size
maxTankSizes[DUNE_BUGGY] = 120; //migrade type 1 tank size
maxTankSizes[MIDGRADE_TYPE2] = 110; //midgrade type 2 tank size
maxTankSizes[MIDGRADE_TYPE3] = 100; //midgrade type 3 tank size
maxTankSizes[HATCHBACK] = 90; //regular type 1 tank size
maxTankSizes[REGULAR_TYPE2] = 70; //regular type 2 tank size
maxTankSizes[REGULAR_TYPE3] = 40; //regular type 3 tank size
maxBznTankSizeOfPremiumCarWithIndex[1] = 200; //SUV tank size
maxBznTankSizeOfPremiumCarWithIndex[2] = 450; //Tanker tank size
maxBznTankSizeOfPremiumCarWithIndex[3] = 300; //Hovercraft tank size
maxBznTankSizeOfPremiumCarWithIndex[4] = 200; //Tank tank size
maxBznTankSizeOfPremiumCarWithIndex[5] = 250; //Lambo tank size
maxBznTankSizeOfMidGradeCarWithIndex[1] = 100; //migrade type 1 tank size
maxBznTankSizeOfMidGradeCarWithIndex[2] = 110; //midgrade type 2 tank size
maxBznTankSizeOfMidGradeCarWithIndex[3] = 120; //midgrade type 3 tank size
maxBznTankSizeOfRegularCarWithIndex[1] = 40; //regular type 1 tank size
maxBznTankSizeOfRegularCarWithIndex[2] = 70; //regular type 2 tank size
maxBznTankSizeOfRegularCarWithIndex[3] = 90; //regular type 3 tank size
isTypeSpecial[HOVERCRAFT_TYPE] = true;
isTypeSpecial[TANK_TYPE] = true;
isTypeSpecial[LAMBO_TYPE] = true;
}
function isCarSpecial(uint256 tokenId) public view returns (bool) {
return isSpecial[tokenId];
}
function getCarType(uint256 tokenId) public view returns (uint) {
return carType[tokenId];
}
function mint(uint256 _tokenId, string _metadata, uint cType, uint256 tankSize, address newOwner) public onlyFactory {
//Since any invalid car type would have a total supply of 0
//This require will also enforce that a valid cType is given
require(carTypeSupply[cType] < carTypeTotalSupply[cType], "This type has reached total supply");
//This will enforce the tank size is less than the max
require(tankSize <= maxTankSizes[cType], "Tank size provided bigger than max for this type");
if (isPremium(cType)) {
premiumTotalSupplyForCar[cType].push(_tokenId);
} else if (isMidGrade(cType)) {
midGradeTotalSupplyForCar[cType].push(_tokenId);
} else {
regularTotalSupplyForCar[cType].push(_tokenId);
}
super._mint(newOwner, _tokenId);
super._setTokenURI(_tokenId, _metadata);
carType[_tokenId] = cType;
isSpecial[_tokenId] = isTypeSpecial[cType];
carTypeSupply[cType] = carTypeSupply[cType] + 1;
tankSizes[_tokenId] = tankSize;
}
function isPremium(uint cType) public pure returns (bool) {
return cType == SUV_TYPE || cType == TANKER_TYPE || cType == HOVERCRAFT_TYPE || cType == TANK_TYPE || cType == LAMBO_TYPE;
}
function isMidGrade(uint cType) public pure returns (bool) {
return cType == DUNE_BUGGY || cType == MIDGRADE_TYPE2 || cType == MIDGRADE_TYPE3;
}
function isRegular(uint cType) public pure returns (bool) {
return cType == HATCHBACK || cType == REGULAR_TYPE2 || cType == REGULAR_TYPE3;
}
function getTotalSupplyForType(uint cType) public view returns (uint256) {
return carTypeSupply[cType];
}
function getPremiumCarsForVariant(uint variant) public view returns (uint[]) {
return premiumTotalSupplyForCar[variant];
}
function getMidgradeCarsForVariant(uint variant) public view returns (uint[]) {
return midGradeTotalSupplyForCar[variant];
}
function getRegularCarsForVariant(uint variant) public view returns (uint[]) {
return regularTotalSupplyForCar[variant];
}
function getPremiumCarSupply(uint variant) public view returns (uint) {
return premiumTotalSupplyForCar[variant].length;
}
function getMidgradeCarSupply(uint variant) public view returns (uint) {
return midGradeTotalSupplyForCar[variant].length;
}
function getRegularCarSupply(uint variant) public view returns (uint) {
return regularTotalSupplyForCar[variant].length;
}
function exists(uint256 _tokenId) public view returns (bool) {
return super._exists(_tokenId);
}
}
| regular type 2 tank size
| maxTankSizes[REGULAR_TYPE2] = 70; | 1,752,810 | [
1,
16819,
618,
576,
268,
2304,
963,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
943,
56,
2304,
11923,
63,
5937,
19545,
67,
2399,
22,
65,
273,
16647,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
Contract to enable the management of private fungible token (ERC-20) transactions using zk-SNARKs.
@Author Westlad, Chaitanya-Konda, iAmMichaelConnor
*/
pragma solidity ^0.5.8;
//TODO: Use openzeppelin interfaces inside the timber service
import "./ERC165Compatible.sol";
import "./MerkleTree.sol";
import "./IShield.sol";
import "./IVerifier.sol";
import "./Registrar.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
contract Shield is Ownable, MerkleTree, ERC165Compatible, Registrar, IShield {
// ENUMS:
enum TransactionTypes { CreateMSA, CreatePO }
// EVENTS:
// Observers may wish to listen for nullification of commitments:
event NewCommitment(bytes32 newCommitment);
event UpdatedCommitment(bytes32 nullifier, bytes32 newCommitment);
event DeletedCommitment(bytes32 nullifier);
// Observers may wish to listen for zkSNARK-related changes:
event VerifierChanged(address newVerifierContract);
event VkChanged(TransactionTypes txType);
// For testing only. This SHOULD be deleted before mainnet deployment:
event GasUsed(uint256 byShieldContract, uint256 byVerifierContract);
// CONTRACT INSTANCES:
IVerifier private verifier; // the verification smart contract
IERC20 private erc20ContractInstance; // the ERC-20 token contract
// PRIVATE TRANSACTIONS' PUBLIC STATES:
mapping(bytes32 => bytes32) public commitments; // store commitments
mapping(bytes32 => bytes32) public nullifiers; // store nullifiers of spent commitments
mapping(bytes32 => bytes32) public roots; // holds each root we've calculated so that we can pull the one relevant to the prover
bytes32 public latestRoot; // holds the index for the latest root so that the prover can provide it later and this contract can look up the relevant root
// VERIFICATION KEY STORAGE:
mapping(uint => uint256[]) public vks; // mapped to by an enum uint(TransactionTypes):
// FUNCTIONS:
constructor(address _verifier, address _erc1820) public ERC165Compatible() Registrar(_erc1820) {
verifier = IVerifier(_verifier);
setInterfaces();
setInterfaceImplementation("IShield", address(this));
}
function setInterfaces() public onlyOwner returns (bool) {
supportedInterfaces[this.changeVerifier.selector ^
this.getVerifier.selector ^
this.createMSA.selector ^
this.createPO.selector] = true;
return true;
}
function getInterfaces() external pure returns (bytes4) {
return this.changeVerifier.selector ^
this.getVerifier.selector ^
this.createMSA.selector ^
this.createPO.selector;
}
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return supportedInterfaces[interfaceId];
}
function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32) {
return ERC1820_ACCEPT_MAGIC;
}
function assignManager(address _newManager) onlyOwner external {
assignManagement(_newManager);
}
/**
self destruct
*/
function close() external onlyOwner returns (bool) {
selfdestruct(address(uint160(msg.sender)));
return true;
}
/**
function to change the address of the underlying Verifier contract
*/
function changeVerifier(address _verifier) external onlyOwner returns (bool) {
verifier = IVerifier(_verifier);
emit VerifierChanged(_verifier);
return true;
}
/**
returns the verifier-interface contract address that this shield contract is calling
*/
function getVerifier() external view returns (address) {
return address(verifier);
}
/**
Stores verification keys (for the 'mint', 'transfer' and 'burn' computations).
*/
function registerVerificationKey(
uint256[] calldata _vk,
TransactionTypes _txType
) external onlyOwner returns (bytes32) {
// CAUTION: we do not prevent overwrites of vk's. Users must listen for the emitted event to detect updates to a vk.
vks[uint(_txType)] = _vk;
emit VkChanged(_txType);
}
/**
createMSA
*/
function createMSA(
uint256[] calldata _proof,
uint256[] calldata _inputs,
bytes32 _newMSACommitment
) external returns (bool) {
// gas measurement:
uint256 gasCheckpoint = gasleft();
// Check that the publicInputHash equals the hash of the 'public inputs':
bytes31 publicInputHash = bytes31(bytes32(_inputs[0]) << 8);
bytes31 publicInputHashCheck = bytes31(sha256(abi.encodePacked(_newMSACommitment)) << 8);
require(publicInputHashCheck == publicInputHash, "publicInputHash cannot be reconciled");
// gas measurement:
uint256 gasUsedByShieldContract = gasCheckpoint - gasleft();
gasCheckpoint = gasleft();
// verify the proof
bool result = verifier.verify(_proof, _inputs, vks[uint(TransactionTypes.CreateMSA)]);
require(result, "The proof has not been verified by the contract");
// gas measurement:
uint256 gasUsedByVerifierContract = gasCheckpoint - gasleft();
gasCheckpoint = gasleft();
// check inputs vs on-chain states
// COMMENTED OUT THE BELOW, FOR QUICKER REPEATED TESTING.
// require(commitments[_newMSACommitment] == 0, "The MSA commitment already exists!");
// update contract states
commitments[_newMSACommitment] = _newMSACommitment;
latestRoot = insertLeaf(_newMSACommitment); // recalculate the root of the merkleTree as it's now different
roots[latestRoot] = latestRoot; // and save the new root to the list of roots
emit NewCommitment(_newMSACommitment);
// gas measurement:
gasUsedByShieldContract = gasUsedByShieldContract + gasCheckpoint - gasleft();
emit GasUsed(gasUsedByShieldContract, gasUsedByVerifierContract);
return true;
}
/**
createPO
*/
function createPO(
uint256[] calldata _proof,
uint256[] calldata _inputs,
bytes32 _root,
bytes32 _nullifierOfOldMSACommitment,
bytes32 _newMSACommitment,
bytes32 _newPOCommitment
) external returns(bool) {
// gas measurement:
uint256[3] memory gasUsed; // array needed to stay below local stack limit
gasUsed[0] = gasleft();
// Check that the publicInputHash equals the hash of the 'public inputs':
bytes31 publicInputHash = bytes31(bytes32(_inputs[0]) << 8);
bytes31 publicInputHashCheck = bytes31(sha256(abi.encodePacked(_root, _nullifierOfOldMSACommitment, _newMSACommitment, _newPOCommitment)) << 8);
require(publicInputHashCheck == publicInputHash, "publicInputHash cannot be reconciled");
// gas measurement:
gasUsed[1] = gasUsed[0] - gasleft();
gasUsed[0] = gasleft();
// verify the proof
bool result = verifier.verify(_proof, _inputs, vks[uint(TransactionTypes.CreatePO)]);
require(result, "The proof has not been verified by the contract");
// gas measurement:
gasUsed[2] = gasUsed[0] - gasleft();
gasUsed[0] = gasleft();
// check inputs vs on-chain states
require(roots[_root] == _root, "The input root has never been the root of the Merkle Tree");
require(_newMSACommitment != _newPOCommitment, "The new commitments (_newMSACommitment and _newPOCommitment) must be different!"); // Is this check necessary?
require(commitments[_newMSACommitment] == 0, "The MSA commitment already exists!");
require(nullifiers[_nullifierOfOldMSACommitment] == 0, "The MSA commitment (which is being updated) has already been nullified!");
require(commitments[_newPOCommitment] == 0, "The PO commitment already exists!");
// update contract states
nullifiers[_nullifierOfOldMSACommitment] = _nullifierOfOldMSACommitment; //remember we spent it
bytes32[] memory leaves = new bytes32[](2);
leaves[0] = _newMSACommitment;
leaves[1] = _newPOCommitment;
latestRoot = insertLeaves(leaves); // recalculate the root of the merkleTree as it's now different
roots[latestRoot] = latestRoot; // and save the new root to the list of roots
emit UpdatedCommitment(_nullifierOfOldMSACommitment, _newMSACommitment);
emit NewCommitment(_newPOCommitment);
// gas measurement:
gasUsed[1] = gasUsed[1] + gasUsed[0] - gasleft();
emit GasUsed(gasUsed[1], gasUsed[2]);
return true;
}
}
| array needed to stay below local stack limit
| uint256[3] memory gasUsed; | 12,730,581 | [
1,
1126,
3577,
358,
23449,
5712,
1191,
2110,
1800,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
63,
23,
65,
3778,
16189,
6668,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*pragma solidity ^0.5.0;
import {HighCardGameState} from './HighCardGameState.sol';
import {IERC20} from '../token/IERC20.sol';
import {SafeMath} from '../math/SafeMath.sol';
contract HeadsUpTables {
using SafeMath for uint256;
// For Domain Separator
bytes32 constant SALT = 0xf1ae92db93da5bd8411028f6531126984a6eb2e7f66b19e5c22d5a7b0fb00bc7;
// Domain separator completed on contract construction
bytes32 public DOMAIN_SEPARATOR;
// Dispute types
uint8 constant public noDispute = 0;
uint8 constant public unresponsiveDispute = 1;
uint8 constant public malformedDispute = 2;
// Action types
uint8 constant public foldAction = 0;
uint8 constant public callAction = 1;
uint8 constant public raiseAction = 2;
uint8 constant public revealAction = 3;
uint8 constant public commitAction = 4;
// Structs
struct State {
uint256[2] currentBalances;
bytes encodedState;
}
struct Claim {
uint8 disputeType;
bytes disputeData;
address proposer;
uint256 redeemTime;
}
struct Table {
bytes32 tableID; // Deterministic ID for any 2 players (same 2 addresses can only play one table at a time)
bytes32 sessionID; // Uniqueness in case same addresses play multiple times
address[2] participants;
uint256 buyIn;
uint256 smallBlind;
uint256 tableExpiration;
uint256 joinExpiration;
State state;
Claim claim;
bool inClaim;
bool isJoined;
uint256 disputeDuration;
}
HighCardGameState poker;
mapping (bytes32 => Table) tables;
mapping (bytes32 => bool) public activeTable;
bytes32[] public activeTables;
IERC20 public token;
/// PUBLIC STATE MODIFYING FUNCTIONS
constructor (address _pokerGameAddress, address _tokenAddress) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(address(this), SALT));
poker = HighCardGameState(_pokerGameAddress);
token = IERC20(_tokenAddress);
}
function openTable(address[2] memory participants, bytes memory openData, uint8[2] memory vs, bytes32[2] memory rs, bytes32[2] memory ss, bytes32 uniqueSessionID) public {
require(participants[0] == msg.sender || participants[1] == msg.sender);
bytes32 tableID = getTableID(participants[0], participants[1]);
bytes32 hash = getTableTransactionHash(tableID, uniqueSessionID, openData);
require(ecrecover(hash, vs[0], rs[0], ss[0]) == participants[0]);
require(ecrecover(hash, vs[1], rs[1], ss[1]) == participants[1]);
require(tables[tableID].tableID != tableID);
require(!activeTable[tableID]);
(uint256 buyIn, uint256 tableDuration, uint256 joinDuration, uint256 disputeDuration) = abi.decode(openData, (uint256, uint256, uint256, uint256));
// Optional (but recommended): require duration minimums
//require(tableDuration >= 600 && disputeDuration >= 600)
require(buyIn%100==0);
require(token.transferFrom(msg.sender, address(this), buyIn));
require(joinDuration<tableDuration);
tables[tableID].tableExpiration = tableDuration.add(now);
tables[tableID].joinExpiration = joinDuration.add(now);
tables[tableID].disputeDuration = disputeDuration;
tables[tableID].tableID = tableID;
tables[tableID].sessionID = uniqueSessionID;
tables[tableID].participants[0] = participants[0];
tables[tableID].participants[1] = participants[1];
tables[tableID].buyIn = buyIn;
tables[tableID].smallBlind = buyIn.div(100);
require(tables[tableID].smallBlind>0);
if (participants[0] == msg.sender) {
tables[tableID].state.currentBalances[0] = buyIn;
} else {
tables[tableID].state.currentBalances[1] = buyIn;
}
activeTable[tableID] = true;
activeTables.push(tableID);
}
function joinTable(address[2] memory participants) public {
bytes32 tableID = getTableID(participants[0], participants[1]);
require(activeTable[tableID]);
require(tables[tableID].tableID == tableID);
require(!tables[tableID].isJoined);
require(now < tables[tableID].joinExpiration);
require(token.transferFrom(msg.sender, address(this), tables[tableID].buyIn));
require(tables[tableID].participants[0] == msg.sender || tables[tableID].participants[1] == msg.sender);
if (tables[tableID].participants[0] == msg.sender) {
require(tables[tableID].state.currentBalances[0] == 0);
tables[tableID].state.currentBalances[0] = tables[tableID].buyIn;
} else {
require(tables[tableID].state.currentBalances[1] == 0);
tables[tableID].state.currentBalances[1] = tables[tableID].buyIn;
}
tables[tableID].state.encodedState = poker.initialEncodedState(tables[tableID].smallBlind);
tables[tableID].isJoined = true;
}
function proposeClaim(bytes32 tableID, bytes memory ClaimData, uint8 v, bytes32 r, bytes32 s) public {
require(activeTable[tableID]);
require(tables[tableID].isJoined);
if (!tables[tableID].inClaim) {
// Must propose a Claim before table expires if no settlment already exists.
require(now < tables[tableID].tableExpiration);
} else {
// If Claim already exists can propose a challenge up until the end of existing Claim dispute period.
require(now < tables[tableID].claim.redeemTime);
}
// Verify and unpack Claim data
(bytes memory finalStateData, address proposer, uint8 disputeType, bytes memory disputeData) = verifyUnpackClaimData(tableID, ClaimData, v, r, s);
// Verify and unpack final state data
bytes memory encodedNewState = verifySignedStateData(tableID, finalStateData);
// Handle Claim
handleClaim(tableID, encodedNewState, proposer, disputeType, disputeData);
}
function claimExpiredTable(bytes32 tableID) public {
require(activeTable[tableID]);
require(!tables[tableID].inClaim);
if (tables[tableID].isJoined) {
if (now > tables[tableID].tableExpiration) {
closeTable(tableID);
}
} else {
if (now > tables[tableID].joinExpiration) {
closeTable(tableID);
}
}
}
function claimExpiredClaim(bytes32 tableID) public {
require(activeTable[tableID]);
require(tables[tableID].inClaim);
require(now > tables[tableID].claim.redeemTime);
require(tables[tableID].claim.proposer == tables[tableID].participants[0] || tables[tableID].claim.proposer == tables[tableID].participants[1]);
if (tables[tableID].claim.proposer == tables[tableID].participants[0]) {
tables[tableID].state.currentBalances[0] = tables[tableID].state.currentBalances[0].add(poker.getPot(tables[tableID].state.encodedState));
} else {
tables[tableID].state.currentBalances[1] = tables[tableID].state.currentBalances[1].add(poker.getPot(tables[tableID].state.encodedState));
}
closeTable(tableID);
}
/// INTERNAL (PROTECTED) STATE MODIFYING FUNCTIONS
function advanceToVerifiedState(bytes32 tableID, bytes memory encodedState) internal {
tables[tableID].state.encodedState = encodedState;
tables[tableID].state.currentBalances = poker.getBalances(encodedState);
}
function handleClaim(bytes32 tableID, bytes memory encodedNewState, address proposer, uint8 disputeType, bytes memory disputeData) internal {
require(poker.isValidStateFastForward(tables[tableID].state.encodedState, encodedNewState, tables[tableID].participants, tables[tableID].smallBlind));
advanceToVerifiedState(tableID, encodedNewState);
if (disputeType==noDispute && poker.getActionType(tables[tableID].state.encodedState)!=commitAction) {
require(false);
} else if (disputeType==noDispute && poker.getActionType(tables[tableID].state.encodedState)==commitAction && (tables[tableID].state.currentBalances[0]==0 || tables[tableID].state.currentBalances[1]==0)) {
closeTable(tableID);
} else if (disputeType==noDispute || (disputeType == unresponsiveDispute && verifyUnresponsiveDispute(tableID, disputeData, proposer))) {
tables[tableID].inClaim = true;
uint256 redeemTime = tables[tableID].disputeDuration.add(now);
tables[tableID].claim = Claim({proposer: proposer, disputeType: disputeType, disputeData: disputeData, redeemTime: redeemTime});
} else if (disputeType==malformedDispute && verifyMalformedDispute(tableID, disputeData, proposer)) {
if (proposer == tables[tableID].participants[0]) {
tables[tableID].state.currentBalances[0] = tables[tableID].state.currentBalances[0].add(poker.getPot(tables[tableID].state.encodedState));
} else if (proposer == tables[tableID].participants[1]) {
tables[tableID].state.currentBalances[1] = tables[tableID].state.currentBalances[1].add(poker.getPot(tables[tableID].state.encodedState));
} else {
require(false);
}
closeTable(tableID);
} else {
require(false);
}
}
function closeTable(bytes32 tableID) internal {
uint256 amount1 = tables[tableID].state.currentBalances[0];
uint256 amount2 = tables[tableID].state.currentBalances[1];
address p1 = tables[tableID].participants[0];
address p2 = tables[tableID].participants[1];
if (tables[tableID].isJoined) {
require(amount1.add(amount2) == tables[tableID].buyIn.mul(2));
} else {
require(amount1.add(amount2) == tables[tableID].buyIn);
}
delete tables[tableID];
delete activeTable[tableID];
for (uint256 i=0; i<activeTables.length; i++) {
if (activeTables[i] == tableID) {
activeTables[i] = activeTables[activeTables.length-1];
delete activeTables[activeTables.length-1];
activeTables.length--;
}
}
require(token.transfer(p1, amount1));
require(token.transfer(p2, amount2));
}
/// PUBLIC VIEW/PURE FUNCTIONS
function getTableID(address participant1, address participant2) public view returns (bytes32) {
require(participant1<participant2);
return keccak256(abi.encodePacked(DOMAIN_SEPARATOR, participant1, participant2));
}
function getTableTransactionHash(bytes32 tableID, bytes32 sessionID, bytes memory txData) public pure returns (bytes32) {
return prefixedHash(tableID, sessionID, keccak256(txData));
}
function getTableOverview(bytes32 tableID) public view returns (address[2] memory, uint256[4] memory, bool[2] memory) {
require(activeTable[tableID]);
uint256[4] memory nums;
nums[0] = tables[tableID].buyIn;
nums[1] = tables[tableID].tableExpiration;
nums[2] = tables[tableID].joinExpiration;
nums[3] = tables[tableID].disputeDuration;
bool[2] memory bools;
bools[0] = tables[tableID].isJoined;
bools[1] = tables[tableID].inClaim;
return (tables[tableID].participants, nums, bools);
}
function getTableClaim(bytes32 tableID) public view returns (uint8, address, uint256, bytes memory) {
require(activeTable[tableID]);
require(tables[tableID].inClaim);
return (tables[tableID].claim.disputeType, tables[tableID].claim.proposer, tables[tableID].claim.redeemTime, tables[tableID].claim.disputeData);
}
function getTableState(bytes32 tableID) public view returns (bytes memory) {
require(activeTable[tableID]);
return tables[tableID].state.encodedState;
}
function verifySignedStateData(bytes32 tableID, bytes memory stateData) public view returns (bytes memory) {
(bytes memory encodedState, uint8[2] memory vs, bytes32[2] memory rs, bytes32[2] memory ss) = abi.decode(stateData, (bytes, uint8[2], bytes32[2], bytes32[2]));
bytes32 hash = getOpenTableTransactionHash(tableID, encodedState);
require(ecrecover(hash, vs[0], rs[0], ss[0]) == tables[tableID].participants[0]);
require(ecrecover(hash, vs[1], rs[1], ss[1]) == tables[tableID].participants[1]);
return encodedState;
}
function verifyHalfSignedStateData(bytes32 tableID, bytes memory stateData, address signer) public view returns (bytes memory) {
(bytes memory encodedState, uint8 v, bytes32 r, bytes32 s) = abi.decode(stateData, (bytes, uint8, bytes32, bytes32));
bytes32 hash = getOpenTableTransactionHash(tableID, encodedState);
require(ecrecover(hash, v, r, s) == signer);
return encodedState;
}
function verifyUnpackClaimData(bytes32 tableID, bytes memory ClaimData, uint8 v, bytes32 r, bytes32 s) public view returns (bytes memory, address, uint8, bytes memory) {
(bytes memory finalStateData, address proposer, uint8 disputeType, bytes memory disputeData) = abi.decode(ClaimData, (bytes, address, uint8, bytes));
require(proposer==tables[tableID].participants[0] || proposer==tables[tableID].participants[1]);
bytes32 hash = getOpenTableTransactionHash(tableID, ClaimData);
require(ecrecover(hash, v, r, s)==proposer);
return (finalStateData, proposer, disputeType, disputeData);
}
function verifyUnresponsiveDispute(bytes32 tableID, bytes memory disputeData, address proposer) public view returns (bool) {
bytes memory encodedNewState = verifyHalfSignedStateData(tableID, disputeData, proposer);
return poker.isValidStateTransition(tables[tableID].state.encodedState, encodedNewState, tables[tableID].participants, tables[tableID].smallBlind);
}
function verifyMalformedDispute(bytes32 tableID, bytes memory disputeData, address proposer) public view returns (bool) {
address signer = tables[tableID].participants[0];
if (proposer == tables[tableID].participants[0]) {
signer = tables[tableID].participants[1];
}
bytes memory encodedNewState = verifyHalfSignedStateData(tableID, disputeData, signer);
return !poker.isValidStateTransition(tables[tableID].state.encodedState, encodedNewState, tables[tableID].participants, tables[tableID].smallBlind);
}
/// INTERNAL VIEW/PURE FUNCTIONS
function getOpenTableTransactionHash(bytes32 tableID, bytes memory txData) internal view returns (bytes32) {
return prefixedHash(tableID, tables[tableID].sessionID, keccak256(txData));
}
function prefixedHash(bytes32 tableID, bytes32 sessionID, bytes32 txHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", tableID, sessionID, txHash));
}
}*/ | Verify and unpack final state data | bytes memory encodedNewState = verifySignedStateData(tableID, finalStateData);
| 7,281,839 | [
1,
8097,
471,
6167,
727,
919,
501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1731,
3778,
3749,
1908,
1119,
273,
3929,
12294,
1119,
751,
12,
2121,
734,
16,
727,
1119,
751,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/src/common/lifecycle/Killable.sol
pragma solidity ^0.5.0;
/**
* A module that allows contracts to self-destruct.
*/
contract Killable {
address payable public _owner;
/**
* Initialized with the deployer as the owner.
*/
constructor() internal {
_owner = msg.sender;
}
/**
* Self-destruct the contract.
* This function can only be executed by the owner.
*/
function kill() public {
require(msg.sender == _owner, "only owner method");
selfdestruct(_owner);
}
}
// File: @openzeppelin/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 should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/src/common/interface/IGroup.sol
pragma solidity ^0.5.0;
contract IGroup {
function isGroup(address _addr) public view returns (bool);
function addGroup(address _addr) external;
function getGroupKey(address _addr) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("_group", _addr));
}
}
// File: contracts/src/common/validate/AddressValidator.sol
pragma solidity ^0.5.0;
/**
* A module that provides common validations patterns.
*/
contract AddressValidator {
string constant errorMessage = "this is illegal address";
/**
* Validates passed address is not a zero address.
*/
function validateIllegalAddress(address _addr) external pure {
require(_addr != address(0), errorMessage);
}
/**
* Validates passed address is included in an address set.
*/
function validateGroup(address _addr, address _groupAddr) external view {
require(IGroup(_groupAddr).isGroup(_addr), errorMessage);
}
/**
* Validates passed address is included in two address sets.
*/
function validateGroups(
address _addr,
address _groupAddr1,
address _groupAddr2
) external view {
if (IGroup(_groupAddr1).isGroup(_addr)) {
return;
}
require(IGroup(_groupAddr2).isGroup(_addr), errorMessage);
}
/**
* Validates that the address of the first argument is equal to the address of the second argument.
*/
function validateAddress(address _addr, address _target) external pure {
require(_addr == _target, errorMessage);
}
/**
* Validates passed address equals to the two addresses.
*/
function validateAddresses(
address _addr,
address _target1,
address _target2
) external pure {
if (_addr == _target1) {
return;
}
require(_addr == _target2, errorMessage);
}
/**
* Validates passed address equals to the three addresses.
*/
function validate3Addresses(
address _addr,
address _target1,
address _target2,
address _target3
) external pure {
if (_addr == _target1) {
return;
}
if (_addr == _target2) {
return;
}
require(_addr == _target3, errorMessage);
}
}
// File: contracts/src/common/validate/UsingValidator.sol
pragma solidity ^0.5.0;
// prettier-ignore
/**
* Module for contrast handling AddressValidator.
*/
contract UsingValidator {
AddressValidator private _validator;
/**
* Create a new AddressValidator contract when initialize.
*/
constructor() public {
_validator = new AddressValidator();
}
/**
* Returns the set AddressValidator address.
*/
function addressValidator() internal view returns (AddressValidator) {
return _validator;
}
}
// File: contracts/src/common/config/AddressConfig.sol
pragma solidity ^0.5.0;
/**
* A registry contract to hold the latest contract addresses.
* Dev Protocol will be upgradeable by this contract.
*/
contract AddressConfig is Ownable, UsingValidator, Killable {
address public token = 0x98626E2C9231f03504273d55f397409deFD4a093;
address public allocator;
address public allocatorStorage;
address public withdraw;
address public withdrawStorage;
address public marketFactory;
address public marketGroup;
address public propertyFactory;
address public propertyGroup;
address public metricsGroup;
address public metricsFactory;
address public policy;
address public policyFactory;
address public policySet;
address public policyGroup;
address public lockup;
address public lockupStorage;
address public voteTimes;
address public voteTimesStorage;
address public voteCounter;
address public voteCounterStorage;
/**
* Set the latest Allocator contract address.
* Only the owner can execute this function.
*/
function setAllocator(address _addr) external onlyOwner {
allocator = _addr;
}
/**
* Set the latest AllocatorStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the AllocatorStorage contract is not used.
*/
function setAllocatorStorage(address _addr) external onlyOwner {
allocatorStorage = _addr;
}
/**
* Set the latest Withdraw contract address.
* Only the owner can execute this function.
*/
function setWithdraw(address _addr) external onlyOwner {
withdraw = _addr;
}
/**
* Set the latest WithdrawStorage contract address.
* Only the owner can execute this function.
*/
function setWithdrawStorage(address _addr) external onlyOwner {
withdrawStorage = _addr;
}
/**
* Set the latest MarketFactory contract address.
* Only the owner can execute this function.
*/
function setMarketFactory(address _addr) external onlyOwner {
marketFactory = _addr;
}
/**
* Set the latest MarketGroup contract address.
* Only the owner can execute this function.
*/
function setMarketGroup(address _addr) external onlyOwner {
marketGroup = _addr;
}
/**
* Set the latest PropertyFactory contract address.
* Only the owner can execute this function.
*/
function setPropertyFactory(address _addr) external onlyOwner {
propertyFactory = _addr;
}
/**
* Set the latest PropertyGroup contract address.
* Only the owner can execute this function.
*/
function setPropertyGroup(address _addr) external onlyOwner {
propertyGroup = _addr;
}
/**
* Set the latest MetricsFactory contract address.
* Only the owner can execute this function.
*/
function setMetricsFactory(address _addr) external onlyOwner {
metricsFactory = _addr;
}
/**
* Set the latest MetricsGroup contract address.
* Only the owner can execute this function.
*/
function setMetricsGroup(address _addr) external onlyOwner {
metricsGroup = _addr;
}
/**
* Set the latest PolicyFactory contract address.
* Only the owner can execute this function.
*/
function setPolicyFactory(address _addr) external onlyOwner {
policyFactory = _addr;
}
/**
* Set the latest PolicyGroup contract address.
* Only the owner can execute this function.
*/
function setPolicyGroup(address _addr) external onlyOwner {
policyGroup = _addr;
}
/**
* Set the latest PolicySet contract address.
* Only the owner can execute this function.
*/
function setPolicySet(address _addr) external onlyOwner {
policySet = _addr;
}
/**
* Set the latest Policy contract address.
* Only the latest PolicyFactory contract can execute this function.
*/
function setPolicy(address _addr) external {
addressValidator().validateAddress(msg.sender, policyFactory);
policy = _addr;
}
/**
* Set the latest Dev contract address.
* Only the owner can execute this function.
*/
function setToken(address _addr) external onlyOwner {
token = _addr;
}
/**
* Set the latest Lockup contract address.
* Only the owner can execute this function.
*/
function setLockup(address _addr) external onlyOwner {
lockup = _addr;
}
/**
* Set the latest LockupStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the LockupStorage contract is not used as a stand-alone because it is inherited from the Lockup contract.
*/
function setLockupStorage(address _addr) external onlyOwner {
lockupStorage = _addr;
}
/**
* Set the latest VoteTimes contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimes contract is not used.
*/
function setVoteTimes(address _addr) external onlyOwner {
voteTimes = _addr;
}
/**
* Set the latest VoteTimesStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimesStorage contract is not used.
*/
function setVoteTimesStorage(address _addr) external onlyOwner {
voteTimesStorage = _addr;
}
/**
* Set the latest VoteCounter contract address.
* Only the owner can execute this function.
*/
function setVoteCounter(address _addr) external onlyOwner {
voteCounter = _addr;
}
/**
* Set the latest VoteCounterStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteCounterStorage contract is not used as a stand-alone because it is inherited from the VoteCounter contract.
*/
function setVoteCounterStorage(address _addr) external onlyOwner {
voteCounterStorage = _addr;
}
}
// File: contracts/src/common/config/UsingConfig.sol
pragma solidity ^0.5.0;
/**
* Module for using AddressConfig contracts.
*/
contract UsingConfig {
AddressConfig private _config;
/**
* Initialize the argument as AddressConfig address.
*/
constructor(address _addressConfig) public {
_config = AddressConfig(_addressConfig);
}
/**
* Returns the latest AddressConfig instance.
*/
function config() internal view returns (AddressConfig) {
return _config;
}
/**
* Returns the latest AddressConfig address.
*/
function configAddress() external view returns (address) {
return address(_config);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
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/IERC20.sol
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/ERC20.sol
pragma solidity ^0.5.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 {ERC20Mintable}.
*
* 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;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 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
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
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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(
amount,
"ERC20: burn amount exceeds allowance"
)
);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
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: contracts/src/allocator/IAllocator.sol
pragma solidity ^0.5.0;
contract IAllocator {
function calculateMaxRewardsPerBlock() public view returns (uint256);
function beforeBalanceChange(
address _property,
address _from,
address _to
// solium-disable-next-line indentation
) external;
}
// File: contracts/src/property/IProperty.sol
pragma solidity ^0.5.0;
contract IProperty {
function author() external view returns (address);
function withdraw(address _sender, uint256 _value) external;
}
// File: contracts/src/property/Property.sol
pragma solidity ^0.5.0;
// prettier-ignore
/**
* A contract that represents the assets of the user and collects staking from the stakers.
* Property contract inherits ERC20.
* Holders of Property contracts(tokens) receive holder rewards according to their share.
*/
contract Property is
ERC20,
ERC20Detailed,
UsingConfig,
UsingValidator,
IProperty
{
using SafeMath for uint256;
uint8 private constant _property_decimals = 18;
uint256 private constant _supply = 10000000000000000000000000;
address public author;
/**
* Initializes the passed value as AddressConfig address, author address, token name, and token symbol.
*/
constructor(
address _config,
address _own,
string memory _name,
string memory _symbol
)
public
UsingConfig(_config)
ERC20Detailed(_name, _symbol, _property_decimals)
{
/**
* Validates the sender is PropertyFactory contract.
*/
addressValidator().validateAddress(
msg.sender,
config().propertyFactory()
);
/**
* Sets the author.
*/
author = _own;
/**
* Mints to the author 100% of the total supply.
*/
_mint(author, _supply);
}
/**
* Hook on `transfer` and call `Withdraw.beforeBalanceChange` function.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
/**
* Validates the destination is not 0 address.
*/
addressValidator().validateIllegalAddress(_to);
require(_value != 0, "illegal transfer value");
/**
* Calls Withdraw contract via Allocator contract.
* Passing through the Allocator contract is due to the historical reason for the old Property contract.
*/
IAllocator(config().allocator()).beforeBalanceChange(
address(this),
msg.sender,
_to
);
/**
* Calls the transfer of ERC20.
*/
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Hook on `transferFrom` and call `Withdraw.beforeBalanceChange` function.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
/**
* Validates the source and destination is not 0 address.
*/
addressValidator().validateIllegalAddress(_from);
addressValidator().validateIllegalAddress(_to);
require(_value != 0, "illegal transfer value");
/**
* Calls Withdraw contract via Allocator contract.
* Passing through the Allocator contract is due to the historical reason for the old Property contract.
*/
IAllocator(config().allocator()).beforeBalanceChange(
address(this),
_from,
_to
);
/**
* Calls the transfer of ERC20.
*/
_transfer(_from, _to, _value);
/**
* Reduces the allowance amount.
*/
uint256 allowanceAmount = allowance(_from, msg.sender);
_approve(
_from,
msg.sender,
allowanceAmount.sub(
_value,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* Transfers the staking amount to the original owner.
*/
function withdraw(address _sender, uint256 _value) external {
/**
* Validates the sender is Lockup contract.
*/
addressValidator().validateAddress(msg.sender, config().lockup());
/**
* Transfers the passed amount to the original owner.
*/
ERC20 devToken = ERC20(config().token());
devToken.transfer(_sender, _value);
}
}
// File: contracts/src/common/storage/EternalStorage.sol
pragma solidity ^0.5.0;
/**
* Module for persisting states.
* Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key.
*/
contract EternalStorage {
address private currentOwner = msg.sender;
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes32) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**
* Modifiers to validate that only the owner can execute.
*/
modifier onlyCurrentOwner() {
require(msg.sender == currentOwner, "not current owner");
_;
}
/**
* Transfer the owner.
* Only the owner can execute this function.
*/
function changeOwner(address _newOwner) external {
require(msg.sender == currentOwner, "not current owner");
currentOwner = _newOwner;
}
// *** Getter Methods ***
/**
* Returns the value of the `uint256` type that mapped to the given key.
*/
function getUint(bytes32 _key) external view returns (uint256) {
return uIntStorage[_key];
}
/**
* Returns the value of the `string` type that mapped to the given key.
*/
function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
/**
* Returns the value of the `address` type that mapped to the given key.
*/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/**
* Returns the value of the `bytes32` type that mapped to the given key.
*/
function getBytes(bytes32 _key) external view returns (bytes32) {
return bytesStorage[_key];
}
/**
* Returns the value of the `bool` type that mapped to the given key.
*/
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/**
* Returns the value of the `int256` type that mapped to the given key.
*/
function getInt(bytes32 _key) external view returns (int256) {
return intStorage[_key];
}
// *** Setter Methods ***
/**
* Maps a value of `uint256` type to a given key.
* Only the owner can execute this function.
*/
function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner {
uIntStorage[_key] = _value;
}
/**
* Maps a value of `string` type to a given key.
* Only the owner can execute this function.
*/
function setString(bytes32 _key, string calldata _value)
external
onlyCurrentOwner
{
stringStorage[_key] = _value;
}
/**
* Maps a value of `address` type to a given key.
* Only the owner can execute this function.
*/
function setAddress(bytes32 _key, address _value)
external
onlyCurrentOwner
{
addressStorage[_key] = _value;
}
/**
* Maps a value of `bytes32` type to a given key.
* Only the owner can execute this function.
*/
function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner {
bytesStorage[_key] = _value;
}
/**
* Maps a value of `bool` type to a given key.
* Only the owner can execute this function.
*/
function setBool(bytes32 _key, bool _value) external onlyCurrentOwner {
boolStorage[_key] = _value;
}
/**
* Maps a value of `int256` type to a given key.
* Only the owner can execute this function.
*/
function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
// *** Delete Methods ***
/**
* Deletes the value of the `uint256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteUint(bytes32 _key) external onlyCurrentOwner {
delete uIntStorage[_key];
}
/**
* Deletes the value of the `string` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteString(bytes32 _key) external onlyCurrentOwner {
delete stringStorage[_key];
}
/**
* Deletes the value of the `address` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteAddress(bytes32 _key) external onlyCurrentOwner {
delete addressStorage[_key];
}
/**
* Deletes the value of the `bytes32` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBytes(bytes32 _key) external onlyCurrentOwner {
delete bytesStorage[_key];
}
/**
* Deletes the value of the `bool` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBool(bytes32 _key) external onlyCurrentOwner {
delete boolStorage[_key];
}
/**
* Deletes the value of the `int256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteInt(bytes32 _key) external onlyCurrentOwner {
delete intStorage[_key];
}
}
// File: contracts/src/common/storage/UsingStorage.sol
pragma solidity ^0.5.0;
/**
* Module for contrast handling EternalStorage.
*/
contract UsingStorage is Ownable {
address private _storage;
/**
* Modifier to verify that EternalStorage is set.
*/
modifier hasStorage() {
require(_storage != address(0), "storage is not set");
_;
}
/**
* Returns the set EternalStorage instance.
*/
function eternalStorage()
internal
view
hasStorage
returns (EternalStorage)
{
return EternalStorage(_storage);
}
/**
* Returns the set EternalStorage address.
*/
function getStorageAddress() external view hasStorage returns (address) {
return _storage;
}
/**
* Create a new EternalStorage contract.
* This function call will fail if the EternalStorage contract is already set.
* Also, only the owner can execute it.
*/
function createStorage() external onlyOwner {
require(_storage == address(0), "storage is set");
EternalStorage tmp = new EternalStorage();
_storage = address(tmp);
}
/**
* Assigns the EternalStorage contract that has already been created.
* Only the owner can execute this function.
*/
function setStorage(address _storageAddress) external onlyOwner {
_storage = _storageAddress;
}
/**
* Delegates the owner of the current EternalStorage contract.
* Only the owner can execute this function.
*/
function changeOwner(address newOwner) external onlyOwner {
EternalStorage(_storage).changeOwner(newOwner);
}
}
// File: contracts/src/property/PropertyGroup.sol
pragma solidity ^0.5.0;
contract PropertyGroup is UsingConfig, UsingStorage, UsingValidator, IGroup {
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
function addGroup(address _addr) external {
addressValidator().validateAddress(
msg.sender,
config().propertyFactory()
);
require(isGroup(_addr) == false, "already enabled");
eternalStorage().setBool(getGroupKey(_addr), true);
}
function isGroup(address _addr) public view returns (bool) {
return eternalStorage().getBool(getGroupKey(_addr));
}
}
// File: contracts/src/property/IPropertyFactory.sol
pragma solidity ^0.5.0;
contract IPropertyFactory {
function create(
string calldata _name,
string calldata _symbol,
address _author
)
external
returns (
// solium-disable-next-line indentation
address
);
function createAndAuthenticate(
string calldata _name,
string calldata _symbol,
address _market,
string calldata _args1,
string calldata _args2,
string calldata _args3
)
external
returns (
// solium-disable-next-line indentation
bool
);
}
// File: contracts/src/market/IMarket.sol
pragma solidity ^0.5.0;
interface IMarket {
function authenticate(
address _prop,
string calldata _args1,
string calldata _args2,
string calldata _args3,
string calldata _args4,
string calldata _args5
)
external
returns (
// solium-disable-next-line indentation
bool
);
function authenticateFromPropertyFactory(
address _prop,
address _author,
string calldata _args1,
string calldata _args2,
string calldata _args3,
string calldata _args4,
string calldata _args5
)
external
returns (
// solium-disable-next-line indentation
bool
);
function authenticatedCallback(address _property, bytes32 _idHash)
external
returns (address);
function deauthenticate(address _metrics) external;
function schema() external view returns (string memory);
function behavior() external view returns (address);
function enabled() external view returns (bool);
function votingEndBlockNumber() external view returns (uint256);
function toEnable() external;
}
// File: contracts/src/property/PropertyFactory.sol
pragma solidity ^0.5.0;
/**
* A factory contract that creates a new Property contract.
*/
contract PropertyFactory is UsingConfig, IPropertyFactory {
event Create(address indexed _from, address _property);
/**
* Initialize the passed address as AddressConfig address.
*/
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
/**
* Creates a new Property contract.
*/
function create(
string calldata _name,
string calldata _symbol,
address _author
) external returns (address) {
return _create(_name, _symbol, _author);
}
/**
* Creates a new Property contract and authenticate.
* There are too many local variables, so when using this method limit the number of arguments that can be used to authenticate to a maximum of 3.
*/
function createAndAuthenticate(
string calldata _name,
string calldata _symbol,
address _market,
string calldata _args1,
string calldata _args2,
string calldata _args3
) external returns (bool) {
return
IMarket(_market).authenticateFromPropertyFactory(
_create(_name, _symbol, msg.sender),
msg.sender,
_args1,
_args2,
_args3,
"",
""
);
}
/**
* Creates a new Property contract.
*/
function _create(
string memory _name,
string memory _symbol,
address _author
) private returns (address) {
/**
* Creates a new Property contract.
*/
Property property = new Property(
address(config()),
_author,
_name,
_symbol
);
/**
* Adds the new Property contract to the Property address set.
*/
IGroup(config().propertyGroup()).addGroup(address(property));
emit Create(msg.sender, address(property));
return address(property);
}
} | * @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 {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
| 6,151,243 | [
1,
24114,
1879,
348,
7953,
560,
1807,
30828,
5295,
598,
3096,
9391,
4271,
18,
27443,
5295,
316,
348,
7953,
560,
2193,
603,
9391,
18,
1220,
848,
17997,
563,
316,
22398,
16,
2724,
5402,
81,
414,
11234,
6750,
716,
392,
9391,
14183,
392,
555,
16,
1492,
353,
326,
4529,
6885,
316,
3551,
1801,
5402,
11987,
8191,
18,
1375,
9890,
10477,
68,
3127,
3485,
333,
509,
89,
608,
635,
15226,
310,
326,
2492,
1347,
392,
1674,
9391,
87,
18,
11637,
333,
5313,
3560,
434,
326,
22893,
5295,
19229,
4174,
392,
7278,
667,
434,
22398,
16,
1427,
518,
1807,
14553,
358,
999,
518,
3712,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
288,
203,
203,
202,
915,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
11890,
5034,
276,
273,
279,
397,
324,
31,
203,
202,
202,
6528,
12,
71,
1545,
279,
16,
315,
9890,
10477,
30,
2719,
9391,
8863,
203,
203,
202,
202,
2463,
276,
31,
203,
202,
97,
203,
203,
202,
915,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
2463,
720,
12,
69,
16,
324,
16,
315,
9890,
10477,
30,
720,
25693,
9391,
8863,
203,
202,
97,
203,
203,
202,
915,
720,
12,
203,
202,
202,
11890,
5034,
279,
16,
203,
202,
202,
11890,
5034,
324,
16,
203,
202,
202,
1080,
3778,
9324,
203,
202,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
6528,
12,
70,
1648,
279,
16,
9324,
1769,
203,
202,
202,
11890,
5034,
276,
273,
279,
300,
324,
31,
203,
203,
202,
202,
2463,
276,
31,
203,
202,
97,
203,
203,
202,
915,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
430,
261,
69,
422,
374,
13,
288,
203,
1082,
202,
2463,
374,
31,
203,
202,
202,
97,
203,
203,
202,
202,
11890,
5034,
276,
273,
279,
380,
324,
31,
203,
202,
202,
6528,
12,
71,
342,
279,
422,
324,
16,
315,
9890,
10477,
30,
23066,
9391,
8863,
203,
203,
202,
202,
2463,
276,
31,
2
] |
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./interfaces/IVoucherSets.sol";
import "./interfaces/IVouchers.sol";
import "./interfaces/IVoucherKernel.sol";
import {PaymentMethod, VoucherState, VoucherStatus, isStateCommitted, isStateRedemptionSigned, isStateRefunded, isStateExpired, isStatus, determineStatus} from "./UsingHelpers.sol";
//preparing for ERC-1066, ERC-1444, EIP-838
/**
* @title VoucherKernel contract controls the core business logic
* @dev Notes:
* - The usage of block.timestamp is honored since vouchers are defined currently with day-precision.
* See: https://ethereum.stackexchange.com/questions/5924/how-do-ethereum-mining-nodes-maintain-a-time-consistent-with-the-network/5931#5931
*/
// solhint-disable-next-line
contract VoucherKernel is IVoucherKernel, Ownable, Pausable, ReentrancyGuard {
using Address for address;
using SafeMath for uint256;
//ERC1155 contract representing voucher sets
address private voucherSetTokenAddress;
//ERC721 contract representing vouchers;
address private voucherTokenAddress;
//promise for an asset could be reusable, but simplified here for brevity
struct Promise {
bytes32 promiseId;
uint256 nonce; //the asset that is offered
address seller; //the seller who created the promise
//we simplify the value for the demoapp, otherwise voucher details would be packed in one bytes32 field value
uint256 validFrom;
uint256 validTo;
uint256 price;
uint256 depositSe;
uint256 depositBu;
uint256 idx;
}
struct VoucherPaymentMethod {
PaymentMethod paymentMethod;
address addressTokenPrice;
address addressTokenDeposits;
}
address private bosonRouterAddress; //address of the Boson Router contract
address private cashierAddress; //address of the Cashier contract
mapping(bytes32 => Promise) private promises; //promises to deliver goods or services
mapping(address => uint256) private tokenNonces; //mapping between seller address and its own nonces. Every time seller creates supply ID it gets incremented. Used to avoid duplicate ID's
mapping(uint256 => VoucherPaymentMethod) private paymentDetails; // tokenSupplyId to VoucherPaymentMethod
bytes32[] private promiseKeys;
mapping(uint256 => bytes32) private ordersPromise; //mapping between an order (supply a.k.a. VoucherSet) and a promise
mapping(uint256 => VoucherStatus) private vouchersStatus; //recording the vouchers evolution
//ID reqs
mapping(uint256 => uint256) private typeCounters; //counter for ID of a particular type of NFT
uint256 private constant MASK_TYPE = uint256(uint128(~0)) << 128; //the type mask in the upper 128 bits
//1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
uint256 private constant MASK_NF_INDEX = uint128(~0); //the non-fungible index mask in the lower 128
//0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
uint256 private constant TYPE_NF_BIT = 1 << 255; //the first bit represents an NFT type
//1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
uint256 private typeId; //base token type ... 127-bits cover 1.701411835*10^38 types (not differentiating between FTs and NFTs)
/* Token IDs:
Fungibles: 0, followed by 127-bit FT type ID, in the upper 128 bits, followed by 0 in lower 128-bits
<0><uint127: base token id><uint128: 0>
Non-fungible VoucherSets (supply tokens): 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by 0 in lower 128-bits
<1><uint127: base token id><uint128: 0
Non-fungible vouchers: 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by a 1-based index of an NFT token ID.
<1><uint127: base token id><uint128: index of non-fungible>
*/
uint256 private complainPeriod;
uint256 private cancelFaultPeriod;
event LogPromiseCreated(
bytes32 indexed _promiseId,
uint256 indexed _nonce,
address indexed _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _idx
);
event LogVoucherCommitted(
uint256 indexed _tokenIdSupply,
uint256 _tokenIdVoucher,
address _issuer,
address _holder,
bytes32 _promiseId
);
event LogVoucherRedeemed(
uint256 _tokenIdVoucher,
address _holder,
bytes32 _promiseId
);
event LogVoucherRefunded(uint256 _tokenIdVoucher);
event LogVoucherComplain(uint256 _tokenIdVoucher);
event LogVoucherFaultCancel(uint256 _tokenIdVoucher);
event LogExpirationTriggered(uint256 _tokenIdVoucher, address _triggeredBy);
event LogFinalizeVoucher(uint256 _tokenIdVoucher, address _triggeredBy);
event LogBosonRouterSet(address _newBosonRouter, address _triggeredBy);
event LogCashierSet(address _newCashier, address _triggeredBy);
event LogVoucherTokenContractSet(address _newTokenContract, address _triggeredBy);
event LogVoucherSetTokenContractSet(address _newTokenContract, address _triggeredBy);
event LogComplainPeriodChanged(
uint256 _newComplainPeriod,
address _triggeredBy
);
event LogCancelFaultPeriodChanged(
uint256 _newCancelFaultPeriod,
address _triggeredBy
);
event LogVoucherSetFaultCancel(uint256 _tokenIdSupply, address _issuer);
event LogFundsReleased(
uint256 _tokenIdVoucher,
uint8 _type //0 .. payment, 1 .. deposits
);
/**
* @notice Checks that only the BosonRouter contract can call a function
*/
modifier onlyFromRouter() {
require(msg.sender == bosonRouterAddress, "UNAUTHORIZED_BR");
_;
}
/**
* @notice Checks that only the Cashier contract can call a function
*/
modifier onlyFromCashier() {
require(msg.sender == cashierAddress, "UNAUTHORIZED_C");
_;
}
/**
* @notice Checks that only the owver of the specified voucher can call a function
*/
modifier onlyVoucherOwner(uint256 _tokenIdVoucher, address _sender) {
//check authorization
require(
IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher) == _sender,
"UNAUTHORIZED_V"
);
_;
}
modifier notZeroAddress(address _addressToCheck) {
require(_addressToCheck != address(0), "0A");
_;
}
/**
* @notice Construct and initialze the contract. Iniialises associated contract addresses, the complain period, and the cancel or fault period
* @param _bosonRouterAddress address of the associated BosonRouter contract
* @param _cashierAddress address of the associated Cashier contract
* @param _voucherSetTokenAddress address of the associated ERC1155 contract instance
* @param _voucherTokenAddress address of the associated ERC721 contract instance
*/
constructor(address _bosonRouterAddress, address _cashierAddress, address _voucherSetTokenAddress, address _voucherTokenAddress)
notZeroAddress(_bosonRouterAddress)
notZeroAddress(_cashierAddress)
notZeroAddress(_voucherSetTokenAddress)
notZeroAddress(_voucherTokenAddress)
{
bosonRouterAddress = _bosonRouterAddress;
cashierAddress = _cashierAddress;
voucherSetTokenAddress = _voucherSetTokenAddress;
voucherTokenAddress = _voucherTokenAddress;
complainPeriod = 7 * 1 days;
cancelFaultPeriod = 7 * 1 days;
}
/**
* @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency.
* Only BR contract is in control of this function.
*/
function pause() external override onlyFromRouter {
_pause();
}
/**
* @notice Unpause the process of interaction with voucherID's (ERC-721).
* Only BR contract is in control of this function.
*/
function unpause() external override onlyFromRouter {
_unpause();
}
/**
* @notice Creating a new promise for goods or services.
* Can be reused, e.g. for making different batches of these (in the future).
* @param _seller seller of the promise
* @param _validFrom Start of valid period
* @param _validTo End of valid period
* @param _price Price (payment amount)
* @param _depositSe Seller's deposit
* @param _depositBu Buyer's deposit
*/
function createTokenSupplyId(
address _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _price,
uint256 _depositSe,
uint256 _depositBu,
uint256 _quantity
)
external
override
nonReentrant
onlyFromRouter
returns (uint256) {
require(_quantity > 0, "INVALID_QUANTITY");
// solhint-disable-next-line not-rely-on-time
require(_validTo >= block.timestamp + 5 minutes, "INVALID_VALIDITY_TO");
require(_validTo >= _validFrom.add(5 minutes), "VALID_FROM_MUST_BE_AT_LEAST_5_MINUTES_LESS_THAN_VALID_TO");
bytes32 key;
key = keccak256(
abi.encodePacked(_seller, tokenNonces[_seller]++, _validFrom, _validTo, address(this))
);
if (promiseKeys.length > 0) {
require(
promiseKeys[promises[key].idx] != key,
"PROMISE_ALREADY_EXISTS"
);
}
promises[key] = Promise({
promiseId: key,
nonce: tokenNonces[_seller],
seller: _seller,
validFrom: _validFrom,
validTo: _validTo,
price: _price,
depositSe: _depositSe,
depositBu: _depositBu,
idx: promiseKeys.length
});
promiseKeys.push(key);
emit LogPromiseCreated(
key,
tokenNonces[_seller],
_seller,
_validFrom,
_validTo,
promiseKeys.length - 1
);
return createOrder(_seller, key, _quantity);
}
/**
* @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set.
* @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to
* @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN
* @param _tokenPrice token address which will hold the funds for the price of the voucher
* @param _tokenDeposits token address which will hold the funds for the deposits of the voucher
*/
function createPaymentMethod(
uint256 _tokenIdSupply,
PaymentMethod _paymentMethod,
address _tokenPrice,
address _tokenDeposits
) external override onlyFromRouter {
paymentDetails[_tokenIdSupply] = VoucherPaymentMethod({
paymentMethod: _paymentMethod,
addressTokenPrice: _tokenPrice,
addressTokenDeposits: _tokenDeposits
});
}
/**
* @notice Create an order for offering a certain quantity of an asset
* This creates a listing in a marketplace, technically as an ERC-1155 non-fungible token with supply.
* @param _seller seller of the promise
* @param _promiseId ID of a promise (simplified into asset for demo)
* @param _quantity Quantity of assets on offer
*/
function createOrder(
address _seller,
bytes32 _promiseId,
uint256 _quantity
) private returns (uint256) {
//create & assign a new non-fungible type
typeId++;
uint256 tokenIdSupply = TYPE_NF_BIT | (typeId << 128); //upper bit is 1, followed by sequence, leaving lower 128-bits as 0;
ordersPromise[tokenIdSupply] = _promiseId;
IVoucherSets(voucherSetTokenAddress).mint(
_seller,
tokenIdSupply,
_quantity,
""
);
return tokenIdSupply;
}
/**
* @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder
* @param _tokenIdSupply ID of the supply token (ERC-1155)
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
* @param _paymentMethod method being used for that particular order that needs to be fulfilled
*/
function fillOrder(
uint256 _tokenIdSupply,
address _issuer,
address _holder,
PaymentMethod _paymentMethod
)
external
override
onlyFromRouter
nonReentrant
{
require(_doERC721HolderCheck(_issuer, _holder, _tokenIdSupply), "UNSUPPORTED_ERC721_RECEIVED");
PaymentMethod paymentMethod = getVoucherPaymentMethod(_tokenIdSupply);
//checks
require(paymentMethod == _paymentMethod, "Incorrect Payment Method");
checkOrderFillable(_tokenIdSupply, _issuer, _holder);
//close order
uint256 voucherTokenId = extract721(_issuer, _holder, _tokenIdSupply);
emit LogVoucherCommitted(
_tokenIdSupply,
voucherTokenId,
_issuer,
_holder,
getPromiseIdFromVoucherId(voucherTokenId)
);
}
/**
* @notice Check if holder is a contract that supports ERC721
* @dev ERC-721
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0-rc.0/contracts/token/ERC721/ERC721.sol
* @param _from Address of sender
* @param _to Address of recipient
* @param _tokenId ID of the token
*/
function _doERC721HolderCheck(
address _from,
address _to,
uint256 _tokenId
) internal returns (bool) {
if (_to.isContract()) {
try IERC721Receiver(_to).onERC721Received(_msgSender(), _from, _tokenId, "") returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("UNSUPPORTED_ERC721_RECEIVED");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @notice Check order is fillable
* @dev Will throw if checks don't pass
* @param _tokenIdSupply ID of the supply token
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
*/
function checkOrderFillable(
uint256 _tokenIdSupply,
address _issuer,
address _holder
) internal view notZeroAddress(_holder) {
require(_tokenIdSupply != 0, "UNSPECIFIED_ID");
require(
IVoucherSets(voucherSetTokenAddress).balanceOf(_issuer, _tokenIdSupply) > 0,
"OFFER_EMPTY"
);
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
require(
promises[promiseKey].validTo >= block.timestamp,
"OFFER_EXPIRED"
);
}
/**
* @notice Extract a standard non-fungible token ERC-721 from a supply stored in ERC-1155
* @dev Token ID is derived following the same principles for both ERC-1155 and ERC-721
* @param _issuer The address of the token issuer
* @param _to The address of the token holder
* @param _tokenIdSupply ID of the token type
* @return ID of the voucher token
*/
function extract721(
address _issuer,
address _to,
uint256 _tokenIdSupply
) internal returns (uint256) {
IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, 1); // This is hardcoded as 1 on purpose
//calculate tokenId
uint256 voucherTokenId =
_tokenIdSupply | ++typeCounters[_tokenIdSupply];
//set status
vouchersStatus[voucherTokenId].status = determineStatus(
vouchersStatus[voucherTokenId].status,
VoucherState.COMMIT
);
vouchersStatus[voucherTokenId].isPaymentReleased = false;
vouchersStatus[voucherTokenId].isDepositsReleased = false;
//mint voucher NFT as ERC-721
IVouchers(voucherTokenAddress).mint(_to, voucherTokenId);
return voucherTokenId;
}
/* solhint-disable */
/**
* @notice Redemption of the vouchers promise
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function redeem(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
//check status
require(
isStateCommitted(vouchersStatus[_tokenIdVoucher].status),
"ALREADY_PROCESSED"
);
//check validity period
isInValidityPeriod(_tokenIdVoucher);
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp;
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.REDEEM
);
emit LogVoucherRedeemed(
_tokenIdVoucher,
_messageSender,
tPromise.promiseId
);
}
// // // // // // // //
// UNHAPPY PATH
// // // // // // // //
/**
* @notice Refunding a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function refund(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
require(
isStateCommitted(vouchersStatus[_tokenIdVoucher].status),
"INAPPLICABLE_STATUS"
);
//check validity period
isInValidityPeriod(_tokenIdVoucher);
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp;
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.REFUND
);
emit LogVoucherRefunded(_tokenIdVoucher);
}
/**
* @notice Issue a complaint for a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function complain(uint256 _tokenIdVoucher, address _messageSender)
external
override
whenNotPaused
onlyFromRouter
onlyVoucherOwner(_tokenIdVoucher, _messageSender)
{
checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.COMPLAIN);
}
/**
* @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender account that called the fn from the BR contract
*/
function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender)
external
override
onlyFromRouter
whenNotPaused
{
uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher);
require(
getSupplyHolder(tokenIdSupply) == _messageSender,
"UNAUTHORIZED_COF"
);
checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.CANCEL_FAULT);
}
/**
* @notice Check if voucher status can be changed into desired new status. If yes, the waiting period is resetted, depending on what new status is.
* @param _tokenIdVoucher ID of the voucher
* @param _newStatus desired new status, can be {COF, COMPLAIN}
*/
function checkIfApplicableAndResetPeriod(uint256 _tokenIdVoucher, VoucherState _newStatus)
internal
{
uint8 tStatus = vouchersStatus[_tokenIdVoucher].status;
require(
!isStatus(tStatus, VoucherState.FINAL),
"ALREADY_FINALIZED"
);
string memory revertReasonAlready;
string memory revertReasonExpired;
if (_newStatus == VoucherState.COMPLAIN) {
revertReasonAlready = "ALREADY_COMPLAINED";
revertReasonExpired = "COMPLAINPERIOD_EXPIRED";
} else {
revertReasonAlready = "ALREADY_CANCELFAULT";
revertReasonExpired = "COFPERIOD_EXPIRED";
}
require(
!isStatus(tStatus, _newStatus),
revertReasonAlready
);
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
if (
isStateRedemptionSigned(tStatus) ||
isStateRefunded(tStatus)
) {
require(
block.timestamp <=
vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod +
cancelFaultPeriod,
revertReasonExpired
);
} else if (isStateExpired(tStatus)) {
//if redeemed or refunded
require(
block.timestamp <=
tPromise.validTo + complainPeriod + cancelFaultPeriod,
revertReasonExpired
);
} else if (
//if the opposite of what is the desired new state. When doing COMPLAIN we need to check if already in COF (and vice versa), since the waiting periods are different.
// VoucherState.COMPLAIN has enum index value 2, while VoucherState.CANCEL_FAULT has enum index value 1. To check the opposite status we use transformation "% 2 + 1" which maps 2 to 1 and 1 to 2
isStatus(vouchersStatus[_tokenIdVoucher].status, VoucherState((uint8(_newStatus) % 2 + 1))) // making it VoucherState.COMPLAIN or VoucherState.CANCEL_FAULT (opposite to new status)
) {
uint256 waitPeriod = _newStatus == VoucherState.COMPLAIN ? vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod : vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod;
require(
block.timestamp <= waitPeriod,
revertReasonExpired
);
} else if (_newStatus != VoucherState.COMPLAIN && isStateCommitted(tStatus)) {
//if committed only (applicable only in COF)
require(
block.timestamp <=
tPromise.validTo + complainPeriod + cancelFaultPeriod,
"COFPERIOD_EXPIRED"
);
} else {
revert("INAPPLICABLE_STATUS");
}
vouchersStatus[_tokenIdVoucher].status = determineStatus(
tStatus,
_newStatus
);
if (_newStatus == VoucherState.COMPLAIN) {
if (!isStatus(tStatus, VoucherState.CANCEL_FAULT)) {
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart = block
.timestamp; //COF period starts
}
emit LogVoucherComplain(_tokenIdVoucher);
} else {
if (!isStatus(tStatus, VoucherState.COMPLAIN)) {
vouchersStatus[_tokenIdVoucher].complainPeriodStart = block
.timestamp; //complain period starts
}
emit LogVoucherFaultCancel(_tokenIdVoucher);
}
}
/**
* @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange.
* @param _tokenIdSupply ID of the voucher set
* @param _issuer owner of the voucher
*/
function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer)
external
override
onlyFromRouter
nonReentrant
whenNotPaused
returns (uint256)
{
require(getSupplyHolder(_tokenIdSupply) == _issuer, "UNAUTHORIZED_COF");
uint256 remQty = getRemQtyForSupply(_tokenIdSupply, _issuer);
require(remQty > 0, "OFFER_EMPTY");
IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, remQty);
emit LogVoucherSetFaultCancel(_tokenIdSupply, _issuer);
return remQty;
}
// // // // // // // //
// BACK-END PROCESS
// // // // // // // //
/**
* @notice Mark voucher token that the payment was released
* @param _tokenIdVoucher ID of the voucher token
*/
function setPaymentReleased(uint256 _tokenIdVoucher)
external
override
onlyFromCashier
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
vouchersStatus[_tokenIdVoucher].isPaymentReleased = true;
emit LogFundsReleased(_tokenIdVoucher, 0);
}
/**
* @notice Mark voucher token that the deposits were released
* @param _tokenIdVoucher ID of the voucher token
*/
function setDepositsReleased(uint256 _tokenIdVoucher)
external
override
onlyFromCashier
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
vouchersStatus[_tokenIdVoucher].isDepositsReleased = true;
emit LogFundsReleased(_tokenIdVoucher, 1);
}
/**
* @notice Mark voucher token as expired
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerExpiration(uint256 _tokenIdVoucher) external override {
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
require(tPromise.validTo < block.timestamp && isStateCommitted(vouchersStatus[_tokenIdVoucher].status),'INAPPLICABLE_STATUS');
vouchersStatus[_tokenIdVoucher].status = determineStatus(
vouchersStatus[_tokenIdVoucher].status,
VoucherState.EXPIRE
);
emit LogExpirationTriggered(_tokenIdVoucher, msg.sender);
}
/**
* @notice Mark voucher token to the final status
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external override {
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
uint8 tStatus = vouchersStatus[_tokenIdVoucher].status;
require(!isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED");
bool mark;
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
if (isStatus(tStatus, VoucherState.COMPLAIN)) {
if (isStatus(tStatus, VoucherState.CANCEL_FAULT)) {
//if COMPLAIN && COF: then final
mark = true;
} else if (
block.timestamp >=
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart +
cancelFaultPeriod
) {
//if COMPLAIN: then final after cof period
mark = true;
}
} else if (
isStatus(tStatus, VoucherState.CANCEL_FAULT) &&
block.timestamp >=
vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod
) {
//if COF: then final after complain period
mark = true;
} else if (
isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus)
) {
//if RDM/RFND NON_COMPLAIN: then final after complainPeriodStart + complainPeriod
if (
block.timestamp >=
vouchersStatus[_tokenIdVoucher].complainPeriodStart +
complainPeriod
) {
mark = true;
}
} else if (isStateExpired(tStatus)) {
//if EXP NON_COMPLAIN: then final after validTo + complainPeriod
if (block.timestamp >= tPromise.validTo + complainPeriod) {
mark = true;
}
}
require(mark, 'INAPPLICABLE_STATUS');
vouchersStatus[_tokenIdVoucher].status = determineStatus(
tStatus,
VoucherState.FINAL
);
emit LogFinalizeVoucher(_tokenIdVoucher, msg.sender);
}
/* solhint-enable */
// // // // // // // //
// UTILS
// // // // // // // //
/**
* @notice Set the address of the new holder of a _tokenIdSupply on transfer
* @param _tokenIdSupply _tokenIdSupply which will be transferred
* @param _newSeller new holder of the supply
*/
function setSupplyHolderOnTransfer(
uint256 _tokenIdSupply,
address _newSeller
) external override onlyFromCashier {
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
promises[promiseKey].seller = _newSeller;
}
/**
* @notice Set the address of the Boson Router contract
* @param _bosonRouterAddress The address of the BR contract
*/
function setBosonRouterAddress(address _bosonRouterAddress)
external
override
onlyOwner
whenPaused
notZeroAddress(_bosonRouterAddress)
{
bosonRouterAddress = _bosonRouterAddress;
emit LogBosonRouterSet(_bosonRouterAddress, msg.sender);
}
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress)
external
override
onlyOwner
whenPaused
notZeroAddress(_cashierAddress)
{
cashierAddress = _cashierAddress;
emit LogCashierSet(_cashierAddress, msg.sender);
}
/**
* @notice Set the address of the Vouchers token contract, an ERC721 contract
* @param _voucherTokenAddress The address of the Vouchers token contract
*/
function setVoucherTokenAddress(address _voucherTokenAddress)
external
override
onlyOwner
notZeroAddress(_voucherTokenAddress)
whenPaused
{
voucherTokenAddress = _voucherTokenAddress;
emit LogVoucherTokenContractSet(_voucherTokenAddress, msg.sender);
}
/**
* @notice Set the address of the Voucher Sets token contract, an ERC1155 contract
* @param _voucherSetTokenAddress The address of the Vouchers token contract
*/
function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external
override
onlyOwner
notZeroAddress(_voucherSetTokenAddress)
whenPaused
{
voucherSetTokenAddress = _voucherSetTokenAddress;
emit LogVoucherSetTokenContractSet(_voucherSetTokenAddress, msg.sender);
}
/**
* @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _complainPeriod the new value for complain period (in number of seconds)
*/
function setComplainPeriod(uint256 _complainPeriod)
external
override
onlyOwner
{
complainPeriod = _complainPeriod;
emit LogComplainPeriodChanged(_complainPeriod, msg.sender);
}
/**
* @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds)
*/
function setCancelFaultPeriod(uint256 _cancelFaultPeriod)
external
override
onlyOwner
{
cancelFaultPeriod = _cancelFaultPeriod;
emit LogCancelFaultPeriodChanged(_cancelFaultPeriod, msg.sender);
}
// // // // // // // //
// GETTERS
// // // // // // // //
/**
* @notice Get the promise ID at specific index
* @param _idx Index in the array of promise keys
* @return Promise ID
*/
function getPromiseKey(uint256 _idx)
external
view
override
returns (bytes32)
{
return promiseKeys[_idx];
}
/**
* @notice Get the supply token ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the supply token
*/
function getIdSupplyFromVoucher(uint256 _tokenIdVoucher)
public
pure
override
returns (uint256)
{
uint256 tokenIdSupply = _tokenIdVoucher & MASK_TYPE;
require(tokenIdSupply !=0, "INEXISTENT_SUPPLY");
return tokenIdSupply;
}
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher)
public
view
override
returns (bytes32)
{
require(_tokenIdVoucher != 0, "UNSPECIFIED_ID");
uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher);
return promises[ordersPromise[tokenIdSupply]].promiseId;
}
/**
* @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account
* @param _tokenSupplyId Token supply ID
* @param _tokenSupplyOwner holder of the Token Supply
* @return remaining quantity
*/
function getRemQtyForSupply(uint256 _tokenSupplyId, address _tokenSupplyOwner)
public
view
override
returns (uint256)
{
return IVoucherSets(voucherSetTokenAddress).balanceOf(_tokenSupplyOwner, _tokenSupplyId);
}
/**
* @notice Get all necessary funds for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit)
*/
function getOrderCosts(uint256 _tokenIdSupply)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return (
promises[promiseKey].price,
promises[promiseKey].depositSe,
promises[promiseKey].depositBu
);
}
/**
* @notice Get Buyer costs required to make an order for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Buyer's deposit)
*/
function getBuyerOrderCosts(uint256 _tokenIdSupply)
external
view
override
returns (uint256, uint256)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return (promises[promiseKey].price, promises[promiseKey].depositBu);
}
/**
* @notice Get Seller deposit
* @param _tokenIdSupply ID of the supply token
* @return returns sellers deposit
*/
function getSellerDeposit(uint256 _tokenIdSupply)
external
view
override
returns (uint256)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return promises[promiseKey].depositSe;
}
/**
* @notice Get the holder of a supply
* @param _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise.
* @return Address of the holder
*/
function getSupplyHolder(uint256 _tokenIdSupply)
public
view
override
returns (address)
{
bytes32 promiseKey = ordersPromise[_tokenIdSupply];
return promises[promiseKey].seller;
}
/**
* @notice Get promise data not retrieved by other accessor functions
* @param _promiseKey ID of the promise
* @return promise data not returned by other accessor methods
*/
function getPromiseData(bytes32 _promiseKey)
external
view
override
returns (bytes32, uint256, uint256, uint256, uint256 )
{
Promise memory tPromise = promises[_promiseKey];
return (tPromise.promiseId, tPromise.nonce, tPromise.validFrom, tPromise.validTo, tPromise.idx);
}
/**
* @notice Get the current status of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Status of the voucher (via enum)
*/
function getVoucherStatus(uint256 _tokenIdVoucher)
external
view
override
returns (
uint8,
bool,
bool,
uint256,
uint256
)
{
return (
vouchersStatus[_tokenIdVoucher].status,
vouchersStatus[_tokenIdVoucher].isPaymentReleased,
vouchersStatus[_tokenIdVoucher].isDepositsReleased,
vouchersStatus[_tokenIdVoucher].complainPeriodStart,
vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart
);
}
/**
* @notice Get the holder of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Address of the holder
*/
function getVoucherHolder(uint256 _tokenIdVoucher)
external
view
override
returns (address)
{
return IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher);
}
/**
* @notice Get the address of the token where the price for the supply is held
* @param _tokenIdSupply ID of the voucher supply token
* @return Address of the token
*/
function getVoucherPriceToken(uint256 _tokenIdSupply)
external
view
override
returns (address)
{
return paymentDetails[_tokenIdSupply].addressTokenPrice;
}
/**
* @notice Get the address of the token where the deposits for the supply are held
* @param _tokenIdSupply ID of the voucher supply token
* @return Address of the token
*/
function getVoucherDepositToken(uint256 _tokenIdSupply)
external
view
override
returns (address)
{
return paymentDetails[_tokenIdSupply].addressTokenDeposits;
}
/**
* @notice Get the payment method for a particular _tokenIdSupply
* @param _tokenIdSupply ID of the voucher supply token
* @return payment method
*/
function getVoucherPaymentMethod(uint256 _tokenIdSupply)
public
view
override
returns (PaymentMethod)
{
return paymentDetails[_tokenIdSupply].paymentMethod;
}
/**
* @notice Checks whether a voucher is in valid period for redemption (between start date and end date)
* @param _tokenIdVoucher ID of the voucher token
*/
function isInValidityPeriod(uint256 _tokenIdVoucher)
public
view
override
returns (bool)
{
//check validity period
Promise memory tPromise =
promises[getPromiseIdFromVoucherId(_tokenIdVoucher)];
require(tPromise.validFrom <= block.timestamp, "INVALID_VALIDITY_FROM");
require(tPromise.validTo >= block.timestamp, "INVALID_VALIDITY_TO");
return true;
}
/**
* @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred
* @param _tokenIdVoucher ID of the voucher token
*/
function isVoucherTransferable(uint256 _tokenIdVoucher)
external
view
override
returns (bool)
{
return
!(vouchersStatus[_tokenIdVoucher].isPaymentReleased ||
vouchersStatus[_tokenIdVoucher].isDepositsReleased);
}
/**
* @notice Get address of the Boson Router to which this contract points
* @return Address of the Boson Router contract
*/
function getBosonRouterAddress()
external
view
override
returns (address)
{
return bosonRouterAddress;
}
/**
* @notice Get address of the Cashier contract to which this contract points
* @return Address of the Cashier contract
*/
function getCashierAddress()
external
view
override
returns (address)
{
return cashierAddress;
}
/**
* @notice Get the token nonce for a seller
* @param _seller Address of the seller
* @return The seller's nonce
*/
function getTokenNonce(address _seller)
external
view
override
returns (uint256)
{
return tokenNonces[_seller];
}
/**
* @notice Get the current type Id
* @return type Id
*/
function getTypeId()
external
view
override
returns (uint256)
{
return typeId;
}
/**
* @notice Get the complain period
* @return complain period
*/
function getComplainPeriod()
external
view
override
returns (uint256)
{
return complainPeriod;
}
/**
* @notice Get the cancel or fault period
* @return cancel or fault period
*/
function getCancelFaultPeriod()
external
view
override
returns (uint256)
{
return cancelFaultPeriod;
}
/**
* @notice Get the promise ID from a voucher set
* @param _tokenIdSupply ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromSupplyId(uint256 _tokenIdSupply)
external
view
override
returns (bytes32)
{
return ordersPromise[_tokenIdSupply];
}
/**
* @notice Get the address of the Vouchers token contract, an ERC721 contract
* @return Address of Vouchers contract
*/
function getVoucherTokenAddress()
external
view
override
returns (address)
{
return voucherTokenAddress;
}
/**
* @notice Get the address of the VoucherSets token contract, an ERC155 contract
* @return Address of VoucherSets contract
*/
function getVoucherSetTokenAddress()
external
view
override
returns (address)
{
return voucherSetTokenAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev 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.7.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 () {
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.7.0;
import "./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
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
interface IVoucherSets is IERC1155, IERC1155MetadataURI {
/**
* @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency.
* All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed.
* There is special function for withdrawing funds if contract is paused.
*/
function pause() external;
/**
* @notice Unpause the Cashier && the Voucher Kernel contracts.
* All functions related to creating new batch, requestVoucher or withdraw will be unpaused.
*/
function unpause() external;
/**
* @notice Mint an amount of a desired token
* Currently no restrictions as to who is allowed to mint - so, it is external.
* @dev ERC-1155
* @param _to owner of the minted token
* @param _tokenId ID of the token to be minted
* @param _value Amount of the token to be minted
* @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function mint(
address _to,
uint256 _tokenId,
uint256 _value,
bytes calldata _data
) external;
/**
* @notice Burn an amount of tokens with the given ID
* @dev ERC-1155
* @param _account Account which owns the token
* @param _tokenId ID of the token
* @param _value Amount of the token
*/
function burn(
address _account,
uint256 _tokenId,
uint256 _value
) external;
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the Voucher Kernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress() external view returns (address);
/**
* @notice Get the address of Cashier contract
* @return Address of Cashier address
*/
function getCashierAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol";
interface IVouchers is IERC721, IERC721Metadata {
/**
* @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency.
* All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed.
* There is special function for withdrawing funds if contract is paused.
*/
function pause() external;
/**
* @notice Unpause the Cashier && the Voucher Kernel contracts.
* All functions related to creating new batch, requestVoucher or withdraw will be unpaused.
*/
function unpause() external;
/**
* @notice Function to mint tokens.
* @dev ERC-721
* @param _to The address that will receive the minted tokens.
* @param _tokenId The token id to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _tokenId) external returns (bool);
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the Voucher Kernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress() external view returns (address);
/**
* @notice Get the address of Cashier contract
* @return Address of Cashier address
*/
function getCashierAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "./../UsingHelpers.sol";
interface IVoucherKernel {
/**
* @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency.
* Only Cashier contract is in control of this function.
*/
function pause() external;
/**
* @notice Unpause the process of interaction with voucherID's (ERC-721).
* Only Cashier contract is in control of this function.
*/
function unpause() external;
/**
* @notice Creating a new promise for goods or services.
* Can be reused, e.g. for making different batches of these (but not in prototype).
* @param _seller seller of the promise
* @param _validFrom Start of valid period
* @param _validTo End of valid period
* @param _price Price (payment amount)
* @param _depositSe Seller's deposit
* @param _depositBu Buyer's deposit
*/
function createTokenSupplyId(
address _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _price,
uint256 _depositSe,
uint256 _depositBu,
uint256 _quantity
) external returns (uint256);
/**
* @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set.
* @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to
* @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN
* @param _tokenPrice token address which will hold the funds for the price of the voucher
* @param _tokenDeposits token address which will hold the funds for the deposits of the voucher
*/
function createPaymentMethod(
uint256 _tokenIdSupply,
PaymentMethod _paymentMethod,
address _tokenPrice,
address _tokenDeposits
) external;
/**
* @notice Mark voucher token that the payment was released
* @param _tokenIdVoucher ID of the voucher token
*/
function setPaymentReleased(uint256 _tokenIdVoucher) external;
/**
* @notice Mark voucher token that the deposits were released
* @param _tokenIdVoucher ID of the voucher token
*/
function setDepositsReleased(uint256 _tokenIdVoucher) external;
/**
* @notice Redemption of the vouchers promise
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function redeem(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Refunding a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function refund(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Issue a complain for a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function complain(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher set (seller)
*/
function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender)
external;
/**
* @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange.
* @param _tokenIdSupply ID of the voucher
* @param _issuer owner of the voucher
*/
function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer)
external
returns (uint256);
/**
* @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder
* @param _tokenIdSupply ID of the supply token (ERC-1155)
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
* @param _paymentMethod method being used for that particular order that needs to be fulfilled
*/
function fillOrder(
uint256 _tokenIdSupply,
address _issuer,
address _holder,
PaymentMethod _paymentMethod
) external;
/**
* @notice Mark voucher token as expired
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerExpiration(uint256 _tokenIdVoucher) external;
/**
* @notice Mark voucher token to the final status
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external;
/**
* @notice Set the address of the new holder of a _tokenIdSupply on transfer
* @param _tokenIdSupply _tokenIdSupply which will be transferred
* @param _newSeller new holder of the supply
*/
function setSupplyHolderOnTransfer(
uint256 _tokenIdSupply,
address _newSeller
) external;
/**
* @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds)
*/
function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external;
/**
* @notice Set the address of the Boson Router contract
* @param _bosonRouterAddress The address of the BR contract
*/
function setBosonRouterAddress(address _bosonRouterAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Set the address of the Vouchers token contract, an ERC721 contract
* @param _voucherTokenAddress The address of the Vouchers token contract
*/
function setVoucherTokenAddress(address _voucherTokenAddress) external;
/**
* @notice Set the address of the Voucher Sets token contract, an ERC1155 contract
* @param _voucherSetTokenAddress The address of the Voucher Sets token contract
*/
function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external;
/**
* @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _complainPeriod the new value for complain period (in number of seconds)
*/
function setComplainPeriod(uint256 _complainPeriod) external;
/**
* @notice Get the promise ID at specific index
* @param _idx Index in the array of promise keys
* @return Promise ID
*/
function getPromiseKey(uint256 _idx) external view returns (bytes32);
/**
* @notice Get the address of the token where the price for the supply is held
* @param _tokenIdSupply ID of the voucher token
* @return Address of the token
*/
function getVoucherPriceToken(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get the address of the token where the deposits for the supply are held
* @param _tokenIdSupply ID of the voucher token
* @return Address of the token
*/
function getVoucherDepositToken(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get Buyer costs required to make an order for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Buyer's deposit)
*/
function getBuyerOrderCosts(uint256 _tokenIdSupply)
external
view
returns (uint256, uint256);
/**
* @notice Get Seller deposit
* @param _tokenIdSupply ID of the supply token
* @return returns sellers deposit
*/
function getSellerDeposit(uint256 _tokenIdSupply)
external
view
returns (uint256);
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getIdSupplyFromVoucher(uint256 _tokenIdVoucher)
external
pure
returns (uint256);
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher)
external
view
returns (bytes32);
/**
* @notice Get all necessary funds for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit)
*/
function getOrderCosts(uint256 _tokenIdSupply)
external
view
returns (
uint256,
uint256,
uint256
);
/**
* @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account
* @param _tokenSupplyId Token supply ID
* @param _owner holder of the Token Supply
* @return remaining quantity
*/
function getRemQtyForSupply(uint256 _tokenSupplyId, address _owner)
external
view
returns (uint256);
/**
* @notice Get the payment method for a particular _tokenIdSupply
* @param _tokenIdSupply ID of the voucher supply token
* @return payment method
*/
function getVoucherPaymentMethod(uint256 _tokenIdSupply)
external
view
returns (PaymentMethod);
/**
* @notice Get the current status of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Status of the voucher (via enum)
*/
function getVoucherStatus(uint256 _tokenIdVoucher)
external
view
returns (
uint8,
bool,
bool,
uint256,
uint256
);
/**
* @notice Get the holder of a supply
* @param _tokenIdSupply _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise.
* @return Address of the holder
*/
function getSupplyHolder(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get the holder of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Address of the holder
*/
function getVoucherHolder(uint256 _tokenIdVoucher)
external
view
returns (address);
/**
* @notice Checks whether a voucher is in valid period for redemption (between start date and end date)
* @param _tokenIdVoucher ID of the voucher token
*/
function isInValidityPeriod(uint256 _tokenIdVoucher)
external
view
returns (bool);
/**
* @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred
* @param _tokenIdVoucher ID of the voucher token
*/
function isVoucherTransferable(uint256 _tokenIdVoucher)
external
view
returns (bool);
/**
* @notice Get address of the Boson Router contract to which this contract points
* @return Address of the Boson Router contract
*/
function getBosonRouterAddress() external view returns (address);
/**
* @notice Get address of the Cashier contract to which this contract points
* @return Address of the Cashier contract
*/
function getCashierAddress() external view returns (address);
/**
* @notice Get the token nonce for a seller
* @param _seller Address of the seller
* @return The seller's
*/
function getTokenNonce(address _seller) external view returns (uint256);
/**
* @notice Get the current type Id
* @return type Id
*/
function getTypeId() external view returns (uint256);
/**
* @notice Get the complain period
* @return complain period
*/
function getComplainPeriod() external view returns (uint256);
/**
* @notice Get the cancel or fault period
* @return cancel or fault period
*/
function getCancelFaultPeriod() external view returns (uint256);
/**
* @notice Get promise data not retrieved by other accessor functions
* @param _promiseKey ID of the promise
* @return promise data not returned by other accessor methods
*/
function getPromiseData(bytes32 _promiseKey)
external
view
returns (
bytes32,
uint256,
uint256,
uint256,
uint256
);
/**
* @notice Get the promise ID from a voucher set
* @param _tokenIdSupply ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromSupplyId(uint256 _tokenIdSupply)
external
view
returns (bytes32);
/**
* @notice Get the address of the Vouchers token contract, an ERC721 contract
* @return Address of Vouchers contract
*/
function getVoucherTokenAddress() external view returns (address);
/**
* @notice Get the address of the VoucherSets token contract, an ERC155 contract
* @return Address of VoucherSets contract
*/
function getVoucherSetTokenAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
// Those are the payment methods we are using throughout the system.
// Depending on how to user choose to interact with it's funds we store the method, so we could distribute its tokens afterwise
enum PaymentMethod {
ETHETH,
ETHTKN,
TKNETH,
TKNTKN
}
enum VoucherState {FINAL, CANCEL_FAULT, COMPLAIN, EXPIRE, REFUND, REDEEM, COMMIT}
/* Status of the voucher in 8 bits:
[6:COMMITTED] [5:REDEEMED] [4:REFUNDED] [3:EXPIRED] [2:COMPLAINED] [1:CANCELORFAULT] [0:FINAL]
*/
uint8 constant ONE = 1;
struct VoucherDetails {
uint256 tokenIdSupply;
uint256 tokenIdVoucher;
address issuer;
address holder;
uint256 price;
uint256 depositSe;
uint256 depositBu;
uint256 price2pool;
uint256 deposit2pool;
uint256 price2issuer;
uint256 deposit2issuer;
uint256 price2holder;
uint256 deposit2holder;
PaymentMethod paymentMethod;
VoucherStatus currStatus;
}
struct VoucherStatus {
uint8 status;
bool isPaymentReleased;
bool isDepositsReleased;
uint256 complainPeriodStart;
uint256 cancelFaultPeriodStart;
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state.
* @param _status current status of a voucher.
*/
function isStateCommitted(uint8 _status) pure returns (bool) {
return _status == determineStatus(0, VoucherState.COMMIT);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in RedemptionSigned state.
* @param _status current status of a voucher.
*/
function isStateRedemptionSigned(uint8 _status)
pure
returns (bool)
{
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REDEEM);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Refunded state.
* @param _status current status of a voucher.
*/
function isStateRefunded(uint8 _status) pure returns (bool) {
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REFUND);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Expired state.
* @param _status current status of a voucher.
*/
function isStateExpired(uint8 _status) pure returns (bool) {
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.EXPIRE);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks the current status a voucher is at.
* @param _status current status of a voucher.
* @param _idx status to compare.
*/
function isStatus(uint8 _status, VoucherState _idx) pure returns (bool) {
return (_status >> uint8(_idx)) & ONE == 1;
}
/**
* @notice Set voucher status.
* @param _status previous status.
* @param _changeIdx next status.
*/
function determineStatus(uint8 _status, VoucherState _changeIdx)
pure
returns (uint8)
{
return _status | (ONE << uint8(_changeIdx));
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | * @notice Get the promise ID at specific index @param _idx Index in the array of promise keys @return Promise ID/ | function getPromiseKey(uint256 _idx)
external
view
override
returns (bytes32)
{
return promiseKeys[_idx];
}
| 40,247 | [
1,
967,
326,
5109,
1599,
622,
2923,
770,
225,
389,
3465,
225,
3340,
316,
326,
526,
434,
5109,
1311,
327,
1377,
5835,
1599,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1689,
4108,
653,
12,
11890,
5034,
389,
3465,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
3890,
1578,
13,
203,
565,
288,
203,
3639,
327,
5109,
2396,
63,
67,
3465,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
import 'dapple/test.sol';
import 'database.sol';
import 'dappsys/auth.sol';
import 'initial_controller.sol';
contract DappHubSimpleControllerTest is Test, DSAuthModesEnum {
DappHubNameOwnerDB names;
DappHubDB packages;
DappHubSimpleController controller;
Tester T1; address t1;
Tester T2; address t2;
function setUp() {
names = new DappHubNameOwnerDB();
packages = new DappHubDB();
controller = new DappHubSimpleController();
controller.setNameDB(names);
controller.setPackageDB(packages);
packages.updateAuthority(address(controller), DSAuthModes.Owner);
names.updateAuthority(address(controller), DSAuthModes.Owner);
T1 = new Tester(); t1 = address(T1);
T1._target( controller );
T2 = new Tester(); t2 = address(T2);
T2._target( controller );
}
// Should be able to update the name db by us
function testUpdateNameDb() {
var _names = new DappHubNameOwnerDB();
controller.setNameDB(_names);
}
// Should be able to update the package db by us
function testUpdatePackageDb() {
var _packages = new DappHubDB();
controller.setPackageDB(_packages);
}
// Should be able to update a package at the root namespace
function testAuthorizedSetPackage() {
controller.setPackage("foo", 1, 0, 0, "bar");
}
// Unauthorized user should not be able to register names at the global namespace
function testErrorUnauthorizedSetPackage() {
DappHubSimpleController(t1).setPackage("foo", 1, 0, 0, "bar");
}
// Unauthorized user should be able to register names prefixed with 'beta/'
function testUnauthorizedSetBetaPackage() {
DappHubSimpleController(t1).setPackage("beta/foo", 1, 0, 0, "bar");
}
// Registered package not owned by root authorety should not be changable
function testErrorRootAuthorityChangeUnownedPackage() {
DappHubSimpleController(t1).setPackage("beta/foo", 1, 0, 0, "bar");
controller.setPackage("beta/foo", 1, 0, 0, "baz");
}
// Should not be able to transfer a package not owned by us
function testErrorUnauthorizedTransfer() {
controller.transferName("foo", address(0x123));
}
function testSimpleNameRegister() {
controller.setNameOwner('foo', address(this));
DappHubSimpleController(t1).setNameOwner("beta/foo", t1);
}
function testErrorUnauthorizedNameRegister() {
DappHubSimpleController(t1).setNameOwner("foo", t1);
}
function testErrorUnauthorizedNameRegister2() {
DappHubSimpleController(t1).setNameOwner("beta/foo", t1);
controller.setNameOwner('beta/foo', address(this));
}
// Should be able to transfer a package owned by us
function testAuthorizedTransfer() {
controller.setNameOwner('foo', address(this));
controller.transferName("foo", t1);
// DappHubSimpleController(t1).setPackage("foo", 1, 0, 0, "bar");
}
// Should not be able to update a package after transferring it
function testErrorUnauthorizedAfterTransfer() {
controller.setNameOwner('foo', address(this));
controller.transferName("foo", address(t1));
controller.setPackage("foo", 1, 0, 0, "bar");
}
function testUserCanIncreaseVersionNumber() {
DappHubSimpleController(t1).setPackage("beta/foo", 1, 0, 0, "bar");
DappHubSimpleController(t1).setPackage("beta/foo", 1, 0, 1, "baz");
}
function testSetUp() {
DappHubSimpleController controller2 = new DappHubSimpleController();
controller2.setUp();
Tester T3; address t3;
T3 = new Tester(); t3 = address(T3);
T3._target( controller2 );
DappHubSimpleController(t3).setPackage('beta/dapphub_registry', 0, 1, 2, 'QmQPzdfmHRRwvFkL9jJPUQAWz7i5RCn5pKkU2J3rEBBePF');
}
}
| Should be able to update the name db by us | function testUpdateNameDb() {
var _names = new DappHubNameOwnerDB();
controller.setNameDB(_names);
}
| 1,042,791 | [
1,
14309,
506,
7752,
358,
1089,
326,
508,
1319,
635,
584,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1842,
1891,
461,
4331,
1435,
288,
203,
565,
569,
389,
1973,
273,
394,
463,
2910,
8182,
461,
5541,
2290,
5621,
203,
565,
2596,
18,
542,
461,
2290,
24899,
1973,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
library Utils {
//From: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/AddressUtils.sol
/**
* 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;
}
//From: https://github.com/PROPSProject/props-token-distribution/blob/master/contracts/token/ERC865Token.sol
/**
* @notice Hash (keccak256) of the payload used by transferPreSigned
* @param _token address The address of the token.
* @param _to address The address which you want to transfer to.
* @param _value uint256 The amount of tokens to be transferred.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
*/
function transferPreSignedHashing(address _token, address _to, uint256 _value, uint256 _fee,
uint256 _nonce, bytes4 _methodName, bytes _args) internal pure returns (bytes32) {
/* "dbe43fca": transferPreSignedHashing(address,address,address,uint256,uint256,uint256,bytes4,bytes) */
return keccak256(bytes4(0xdbe43fca), _token, _to, _value, _fee, _nonce, _methodName, _args);
}
function transferPreSignedHashing(address _token, address _to, uint256 _value, uint256 _fee,
uint256 _nonce) internal pure returns (bytes32) {
/* "48664c16": transferPreSignedHashing(address,address,address,uint256,uint256,uint256) */
return keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce);
}
/**
* @notice Recover signer address from a message by using his 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) internal 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);
}
}
} | From: https:github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/AddressUtils.sol | library Utils {
function isContract(address addr) internal view returns (bool) {
uint256 size;
return size > 0;
}
assembly { size := extcodesize(addr) }
function transferPreSignedHashing(address _token, address _to, uint256 _value, uint256 _fee,
uint256 _nonce, bytes4 _methodName, bytes _args) internal pure returns (bytes32) {
return keccak256(bytes4(0xdbe43fca), _token, _to, _value, _fee, _nonce, _methodName, _args);
}
function transferPreSignedHashing(address _token, address _to, uint256 _value, uint256 _fee,
uint256 _nonce) internal pure returns (bytes32) {
return keccak256(bytes4(0x48664c16), _token, _to, _value, _fee, _nonce);
}
function recover(bytes32 hash, bytes sig) internal pure returns (address) {bytes32 r; bytes32 s; uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
return ecrecover(hash, v, r, s);
}
}
function recover(bytes32 hash, bytes sig) internal pure returns (address) {bytes32 r; bytes32 s; uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
return ecrecover(hash, v, r, s);
}
}
function recover(bytes32 hash, bytes sig) internal pure returns (address) {bytes32 r; bytes32 s; uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
return ecrecover(hash, v, r, s);
}
}
function recover(bytes32 hash, bytes sig) internal pure returns (address) {bytes32 r; bytes32 s; uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
return ecrecover(hash, v, r, s);
}
}
function recover(bytes32 hash, bytes sig) internal pure returns (address) {bytes32 r; bytes32 s; uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
return ecrecover(hash, v, r, s);
}
}
} else {
} | 888,341 | [
1,
1265,
30,
2333,
30,
6662,
18,
832,
19,
3678,
62,
881,
84,
292,
267,
19,
3190,
94,
881,
84,
292,
267,
17,
30205,
560,
19,
10721,
19,
7525,
19,
16351,
87,
19,
1887,
1989,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
6091,
288,
203,
203,
203,
565,
445,
353,
8924,
12,
2867,
3091,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
963,
31,
203,
3639,
327,
963,
405,
374,
31,
203,
565,
289,
203,
203,
3639,
19931,
288,
963,
519,
1110,
7000,
554,
12,
4793,
13,
289,
203,
203,
565,
445,
7412,
1386,
12294,
2310,
310,
12,
2867,
389,
2316,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
16,
2254,
5034,
389,
21386,
16,
203,
3639,
2254,
5034,
389,
12824,
16,
1731,
24,
389,
2039,
461,
16,
1731,
389,
1968,
13,
2713,
16618,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
3890,
24,
12,
20,
92,
1966,
73,
8942,
74,
5353,
3631,
389,
2316,
16,
389,
869,
16,
389,
1132,
16,
389,
21386,
16,
389,
12824,
16,
389,
2039,
461,
16,
389,
1968,
1769,
203,
203,
565,
289,
203,
565,
445,
7412,
1386,
12294,
2310,
310,
12,
2867,
389,
2316,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
16,
2254,
5034,
389,
21386,
16,
203,
3639,
2254,
5034,
389,
12824,
13,
2713,
16618,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
3890,
24,
12,
20,
92,
24,
5292,
1105,
71,
2313,
3631,
389,
2316,
16,
389,
869,
16,
389,
1132,
16,
389,
21386,
16,
389,
12824,
1769,
203,
203,
565,
289,
203,
565,
445,
5910,
12,
3890,
1578,
1651,
16,
1731,
3553,
13,
2713,
16618,
1135,
261,
2867,
13,
288,
3890,
1578,
436,
31,
1731,
1578,
2
] |
pragma solidity 0.4.24;
contract ExecutionTarget {
uint256 public counter;
function execute() public {
counter += 1;
emit Executed(counter);
}
function setCounter(uint256 x) public {
counter = x;
}
event Executed(uint256 x);
}
pragma solidity 0.4.24;
import "@aragon/os/contracts/acl/ACL.sol";
import "@aragon/os/contracts/kernel/Kernel.sol";
import "@aragon/os/contracts/factory/DAOFactory.sol";
import "@aragon/os/contracts/factory/APMRegistryFactory.sol";
import "@aragon/os/contracts/factory/ENSFactory.sol";
import "@aragon/os/contracts/apm/APMRegistry.sol";
import "@aragon/os/contracts/apm/Repo.sol";
import "@aragon/os/contracts/ens/ENSSubdomainRegistrar.sol";
import "@aragon/os/contracts/lib/ens/ENS.sol";
import "@aragon/os/contracts/lib/ens/AbstractENS.sol";
import "@aragon/os/contracts/lib/ens/PublicResolver.sol";
import "@aragon/test-helpers/contracts/TokenMock.sol";
contract Imports {
// solium-disable-previous-line no-empty-blocks
}
pragma solidity 0.4.24;
import "../apps/AragonApp.sol";
import "../common/ConversionHelpers.sol";
import "../common/TimeHelpers.sol";
import "./ACLSyntaxSugar.sol";
import "./IACL.sol";
import "./IACLOracle.sol";
/* solium-disable function-order */
// Allow public initialize() to be first
contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
*/
bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a;
enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types
struct Param {
uint8 id;
uint8 op;
uint240 value; // even though value is an uint240 it can store addresses
// in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
// op and id take less than 1 byte each so it can be kept in 1 sstore
}
uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200;
uint8 internal constant TIMESTAMP_PARAM_ID = 201;
// 202 is unused
uint8 internal constant ORACLE_PARAM_ID = 203;
uint8 internal constant LOGIC_OP_PARAM_ID = 204;
uint8 internal constant PARAM_VALUE_PARAM_ID = 205;
// TODO: Add execution times param type?
/* Hardcoded constant to save gas
bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0));
*/
bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
bytes32 public constant NO_PERMISSION = bytes32(0);
address public constant ANY_ENTITY = address(-1);
address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager"
string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL";
string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER";
string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER";
// Whether someone has a permission
mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash
mapping (bytes32 => Param[]) internal permissionParams; // params hash => params
// Who is the manager of a permission
mapping (bytes32 => address) internal permissionManager;
event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash);
event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
modifier onlyPermissionManager(address _app, bytes32 _role) {
require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER);
_;
}
modifier noPermissionManager(address _app, bytes32 _role) {
// only allow permission creation (or re-creation) when there is no manager
require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER);
_;
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(address _permissionsCreator) public onlyInit {
initialized();
require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL);
_createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
}
/**
* @dev Creates a permission that wasn't previously set and managed.
* If a created permission is removed it is possible to reset it with createPermission.
* This is the **ONLY** way to create permissions and set managers to permissions that don't
* have a manager.
* In terms of the ACL being initialized, this function implicitly protects all the other
* state-changing external functions, as they all require the sender to be a manager.
* @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _manager Address of the entity that will be able to grant and revoke the permission further.
*/
function createPermission(address _entity, address _app, bytes32 _role, address _manager)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_createPermission(_entity, _app, _role, _manager);
}
/**
* @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
*/
function grantPermission(address _entity, address _app, bytes32 _role)
external
{
grantPermissionP(_entity, _app, _role, new uint256[](0));
}
/**
* @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _params Permission parameters
*/
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
public
onlyPermissionManager(_app, _role)
{
bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
_setPermission(_entity, _app, _role, paramsHash);
}
/**
* @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
* @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity to revoke access from
* @param _app Address of the app in which the role will be revoked
* @param _role Identifier for the group of actions in app being revoked
*/
function revokePermission(address _entity, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermission(_entity, _app, _role, NO_PERMISSION);
}
/**
* @notice Set `_newManager` as the manager of `_role` in `_app`
* @param _newManager Address for the new manager
* @param _app Address of the app in which the permission management is being transferred
* @param _role Identifier for the group of actions being transferred
*/
function setPermissionManager(address _newManager, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(_newManager, _app, _role);
}
/**
* @notice Remove the manager of `_role` in `_app`
* @param _app Address of the app in which the permission is being unmanaged
* @param _role Identifier for the group of actions being unmanaged
*/
function removePermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(address(0), _app, _role);
}
/**
* @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function createBurnedPermission(address _app, bytes32 _role)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function burnPermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Get parameters for permission array length
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return Length of the array
*/
function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) {
return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length;
}
/**
* @notice Get parameter for permission
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @param _index Index of parameter in the array
* @return Parameter (id, op, value)
*/
function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index)
external
view
returns (uint8, uint8, uint240)
{
Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index];
return (param.id, param.op, param.value);
}
/**
* @dev Get manager for permission
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return address of the manager for the permission
*/
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission statu
* @param _who Sender of the original call
* @param _where Address of the app
* @param _where Identifier for a group of actions in app
* @param _how Permission parameters
* @return boolean indicating whether the ACL allows the role or not
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how));
}
function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) {
return true;
}
bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
return true;
}
return false;
}
function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
uint256[] memory empty = new uint256[](0);
return hasPermission(_who, _where, _what, empty);
}
function evalParams(
bytes32 _paramsHash,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) public view returns (bool)
{
if (_paramsHash == EMPTY_PARAM_HASH) {
return true;
}
return _evalParam(_paramsHash, 0, _who, _where, _what, _how);
}
/**
* @dev Internal createPermission for access inside the kernel (on instantiation)
*/
function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
_setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
_setPermissionManager(_manager, _app, _role);
}
/**
* @dev Internal function called to actually save the permission
*/
function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
bool entityHasPermission = _paramsHash != NO_PERMISSION;
bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH;
emit SetPermission(_entity, _app, _role, entityHasPermission);
if (permissionHasParams) {
emit SetPermissionParams(_entity, _app, _role, _paramsHash);
}
}
function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams));
Param[] storage params = permissionParams[paramHash];
if (params.length == 0) { // params not saved before
for (uint256 i = 0; i < _encodedParams.length; i++) {
uint256 encodedParam = _encodedParams[i];
Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
params.push(param);
}
}
return paramHash;
}
function _evalParam(
bytes32 _paramsHash,
uint32 _paramId,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) internal view returns (bool)
{
if (_paramId >= permissionParams[_paramsHash].length) {
return false; // out of bounds
}
Param memory param = permissionParams[_paramsHash][_paramId];
if (param.id == LOGIC_OP_PARAM_ID) {
return _evalLogic(param, _paramsHash, _who, _where, _what, _how);
}
uint256 value;
uint256 comparedTo = uint256(param.value);
// get value
if (param.id == ORACLE_PARAM_ID) {
value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0;
comparedTo = 1;
} else if (param.id == BLOCK_NUMBER_PARAM_ID) {
value = getBlockNumber();
} else if (param.id == TIMESTAMP_PARAM_ID) {
value = getTimestamp();
} else if (param.id == PARAM_VALUE_PARAM_ID) {
value = uint256(param.value);
} else {
if (param.id >= _how.length) {
return false;
}
value = uint256(uint240(_how[param.id])); // force lost precision
}
if (Op(param.op) == Op.RET) {
return uint256(value) > 0;
}
return compare(value, Op(param.op), comparedTo);
}
function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how)
internal
view
returns (bool)
{
if (Op(_param.op) == Op.IF_ELSE) {
uint32 conditionParam;
uint32 successParam;
uint32 failureParam;
(conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value));
bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how);
return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how);
}
uint32 param1;
uint32 param2;
(param1, param2,) = decodeParamsList(uint256(_param.value));
bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how);
if (Op(_param.op) == Op.NOT) {
return !r1;
}
if (r1 && Op(_param.op) == Op.OR) {
return true;
}
if (!r1 && Op(_param.op) == Op.AND) {
return false;
}
bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how);
if (Op(_param.op) == Op.XOR) {
return r1 != r2;
}
return r2; // both or and and depend on result of r2 after checks
}
function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace
if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace
if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace
if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace
if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace
if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace
return false;
}
function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
bytes4 sig = _oracleAddr.canPerform.selector;
// a raw call is required so we can return false if the call reverts, rather than reverting
bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how);
bool ok;
assembly {
// send all available gas; if the oracle eats up all the gas, we will eventually revert
// note that we are currently guaranteed to still have some gas after the call from
// EIP-150's 63/64 gas forward rule
ok := staticcall(gas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0)
}
if (!ok) {
return false;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return false;
}
bool result;
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
result := mload(ptr) // read data at ptr and set it to result
mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr
}
return result;
}
/**
* @dev Internal function that sets management
*/
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
permissionManager[roleHash(_app, _role)] = _newManager;
emit ChangePermissionManager(_app, _role, _newManager);
}
function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("ROLE", _where, _what));
}
function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what));
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./AppStorage.sol";
import "../acl/ACLSyntaxSugar.sol";
import "../common/Autopetrified.sol";
import "../common/ConversionHelpers.sol";
import "../common/ReentrancyGuard.sol";
import "../common/VaultRecoverable.sol";
import "../evmscript/EVMScriptRunner.sol";
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../common/UnstructuredStorage.sol";
import "../kernel/IKernel.sol";
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../acl/IACL.sol";
import "../common/IVaultRecoverable.sol";
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./Petrifiable.sol";
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./Initializable.sol";
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./TimeHelpers.sol";
import "./UnstructuredStorage.sol";
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./Uint256Helpers.sol";
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../common/UnstructuredStorage.sol";
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../lib/token/ERC20.sol";
import "./EtherTokenConstant.sol";
import "./IsContract.sol";
import "./IVaultRecoverable.sol";
import "./SafeERC20.sol";
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
import "../lib/token/ERC20.sol";
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
private
returns (bool)
{
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
/**
* @dev Static call into ERC20.totalSupply().
* Reverts if the call fails for some reason (should never fail).
*/
function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
(bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return totalSupply;
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./IEVMScriptExecutor.sol";
import "./IEVMScriptRegistry.sol";
import "../apps/AppStorage.sol";
import "../kernel/KernelConstants.sol";
import "../common/Initializable.sol";
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./IEVMScriptExecutor.sol";
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IACLOracle {
function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool);
}
pragma solidity 0.4.24;
import "./IKernel.sol";
import "./KernelConstants.sol";
import "./KernelStorage.sol";
import "../acl/IACL.sol";
import "../acl/ACLSyntaxSugar.sol";
import "../common/ConversionHelpers.sol";
import "../common/IsContract.sol";
import "../common/Petrifiable.sol";
import "../common/VaultRecoverable.sol";
import "../factory/AppProxyFactory.sol";
import "../lib/misc/ERCProxy.sol";
// solium-disable-next-line max-len
contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
/* Hardcoded constants to save gas
bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
*/
bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
/**
* @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
* @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
*/
constructor(bool _shouldPetrify) public {
if (_shouldPetrify) {
petrify();
}
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
* @param _baseAcl Address of base ACL app
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
initialized();
// Set ACL base
_setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
// Create ACL instance and attach it as the default ACL app
IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
acl.initialize(_permissionsCreator);
_setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
}
/**
* @dev Create a new instance of an app linked to this kernel
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new instance of an app linked to this kernel and set its base
* implementation if it was not already set
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxy(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Create a new pinned instance of an app linked to this kernel
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new pinned instance of an app linked to this kernel and set
* its base implementation if it was not already set
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxyPinned(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Set the resolving address of an app instance or base implementation
* @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @param _app Address of the app instance or base implementation
* @return ID of app
*/
function setApp(bytes32 _namespace, bytes32 _appId, address _app)
public
auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
{
_setApp(_namespace, _appId, _app);
}
/**
* @dev Set the default vault id for the escape hatch mechanism
* @param _recoveryVaultAppId Identifier of the recovery vault app
*/
function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
{
recoveryVaultAppId = _recoveryVaultAppId;
}
// External access to default app id and namespace constants to mimic default getters for constants
/* solium-disable function-order, mixedcase */
function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
/* solium-enable function-order, mixedcase */
/**
* @dev Get the address of an app instance or base implementation
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @return Address of the app
*/
function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
return apps[_namespace][_appId];
}
/**
* @dev Get the address of the recovery Vault instance (to recover funds)
* @return Address of the Vault
*/
function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
/**
* @dev Get the installed ACL app
* @return ACL app
*/
function acl() public view returns (IACL) {
return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission status
* @param _who Sender of the original call
* @param _where Address of the app
* @param _what Identifier for a group of actions in app
* @param _how Extra data for ACL auth
* @return Boolean indicating whether the ACL allows the role or not.
* Always returns false if the kernel hasn't been initialized yet.
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
IACL defaultAcl = acl();
return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
defaultAcl.hasPermission(_who, _where, _what, _how);
}
function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
require(isContract(_app), ERROR_APP_NOT_CONTRACT);
apps[_namespace][_appId] = _app;
emit SetApp(_namespace, _appId, _app);
}
function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
address app = getApp(_namespace, _appId);
if (app != address(0)) {
// The only way to set an app is if it passes the isContract check, so no need to check it again
require(app == _app, ERROR_INVALID_APP_CHANGE);
} else {
_setApp(_namespace, _appId, _app);
}
}
modifier auth(bytes32 _role, uint256[] memory _params) {
require(
hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
ERROR_AUTH_FAILED
);
_;
}
}
pragma solidity 0.4.24;
contract KernelStorage {
// namespace => app id => address
mapping (bytes32 => mapping (bytes32 => address)) public apps;
bytes32 public recoveryVaultAppId;
}
pragma solidity 0.4.24;
import "../apps/AppProxyUpgradeable.sol";
import "../apps/AppProxyPinned.sol";
contract AppProxyFactory {
event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
return newAppProxy(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), true, _appId);
return proxy;
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
return newAppProxyPinned(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @param _initializePayload Proxy initialization payload
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), false, _appId);
return proxy;
}
}
pragma solidity 0.4.24;
import "./AppProxyBase.sol";
contract AppProxyUpgradeable is AppProxyBase {
/**
* @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
// solium-disable-previous-line no-empty-blocks
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return getAppBase(appId());
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
}
pragma solidity 0.4.24;
import "./AppStorage.sol";
import "../common/DepositableDelegateProxy.sol";
import "../kernel/KernelConstants.sol";
import "../kernel/IKernel.sol";
contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
/**
* @dev Initialize AppProxy
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
setKernel(_kernel);
setAppId(_appId);
// Implicit check that kernel is actually a Kernel
// The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
// occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
// it.
address appCode = getAppBase(_appId);
// If initialize payload is provided, it will be executed
if (_initializePayload.length > 0) {
require(isContract(appCode));
// Cannot make delegatecall as a delegateproxy.delegatedFwd as it
// returns ending execution context and halts contract deployment
require(appCode.delegatecall(_initializePayload));
}
}
function getAppBase(bytes32 _appId) internal view returns (address) {
return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
}
}
pragma solidity 0.4.24;
import "./DelegateProxy.sol";
import "./DepositableStorage.sol";
contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
event ProxyDeposit(address sender, uint256 value);
function () external payable {
uint256 forwardGasThreshold = FWD_GAS_LIMIT;
bytes32 isDepositablePosition = DEPOSITABLE_POSITION;
// Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
// https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
assembly {
// Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
// otherwise continue outside of the assembly block.
if lt(gas, forwardGasThreshold) {
// Only accept the deposit and emit an event if all of the following are true:
// the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
// Equivalent Solidity code for emitting the event:
// emit ProxyDeposit(msg.sender, msg.value);
let logData := mload(0x40) // free memory pointer
mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)
// Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
stop() // Stop. Exits execution context
}
// If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
revert(0, 0)
}
}
address target = implementation();
delegatedFwd(target, msg.data);
}
}
pragma solidity 0.4.24;
import "../common/IsContract.sol";
import "../lib/misc/ERCProxy.sol";
contract DelegateProxy is ERCProxy, IsContract {
uint256 internal constant FWD_GAS_LIMIT = 10000;
/**
* @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
* @param _dst Destination address to perform the delegatecall
* @param _calldata Calldata for the delegatecall
*/
function delegatedFwd(address _dst, bytes _calldata) internal {
require(isContract(_dst));
uint256 fwdGasLimit = FWD_GAS_LIMIT;
assembly {
let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ERCProxy {
uint256 internal constant FORWARDING = 1;
uint256 internal constant UPGRADEABLE = 2;
function proxyType() public pure returns (uint256 proxyTypeId);
function implementation() public view returns (address codeAddr);
}
pragma solidity 0.4.24;
import "./UnstructuredStorage.sol";
contract DepositableStorage {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.depositableStorage.depositable")
bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
function isDepositable() public view returns (bool) {
return DEPOSITABLE_POSITION.getStorageBool();
}
function setDepositable(bool _depositable) internal {
DEPOSITABLE_POSITION.setStorageBool(_depositable);
}
}
pragma solidity 0.4.24;
import "../common/UnstructuredStorage.sol";
import "../common/IsContract.sol";
import "./AppProxyBase.sol";
contract AppProxyPinned is IsContract, AppProxyBase {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.appStorage.pinnedCode")
bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
/**
* @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
setPinnedCode(getAppBase(_appId));
require(isContract(pinnedCode()));
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return pinnedCode();
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return FORWARDING;
}
function setPinnedCode(address _pinnedCode) internal {
PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
}
function pinnedCode() internal view returns (address) {
return PINNED_CODE_POSITION.getStorageAddress();
}
}
pragma solidity 0.4.24;
import "../kernel/IKernel.sol";
import "../kernel/Kernel.sol";
import "../kernel/KernelProxy.sol";
import "../acl/IACL.sol";
import "../acl/ACL.sol";
import "./EVMScriptRegistryFactory.sol";
contract DAOFactory {
IKernel public baseKernel;
IACL public baseACL;
EVMScriptRegistryFactory public regFactory;
event DeployDAO(address dao);
event DeployEVMScriptRegistry(address reg);
/**
* @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`.
* @param _baseKernel Base Kernel
* @param _baseACL Base ACL
* @param _regFactory EVMScriptRegistry factory
*/
constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
// No need to init as it cannot be killed by devops199
if (address(_regFactory) != address(0)) {
regFactory = _regFactory;
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
/**
* @notice Create a new DAO with `_root` set as the initial admin
* @param _root Address that will be granted control to setup DAO permissions
* @return Newly created DAO
*/
function newDAO(address _root) public returns (Kernel) {
Kernel dao = Kernel(new KernelProxy(baseKernel));
if (address(regFactory) == address(0)) {
dao.initialize(baseACL, _root);
} else {
dao.initialize(baseACL, this);
ACL acl = ACL(dao.acl());
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
acl.grantPermission(regFactory, acl, permRole);
acl.createPermission(regFactory, dao, appManagerRole, this);
EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao);
emit DeployEVMScriptRegistry(address(reg));
// Clean up permissions
// First, completely reset the APP_MANAGER_ROLE
acl.revokePermission(regFactory, dao, appManagerRole);
acl.removePermissionManager(dao, appManagerRole);
// Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE
acl.revokePermission(regFactory, acl, permRole);
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
}
emit DeployDAO(address(dao));
return dao;
}
}
pragma solidity 0.4.24;
import "./IKernel.sol";
import "./KernelConstants.sol";
import "./KernelStorage.sol";
import "../common/DepositableDelegateProxy.sol";
import "../common/IsContract.sol";
contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy {
/**
* @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
* can update the reference, which effectively upgrades the contract
* @param _kernelImpl Address of the contract used as implementation for kernel
*/
constructor(IKernel _kernelImpl) public {
require(isContract(address(_kernelImpl)));
apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl;
// Note that emitting this event is important for verifying that a KernelProxy instance
// was never upgraded to a malicious Kernel logic contract over its lifespan.
// This starts the "chain of trust", that can be followed through later SetApp() events
// emitted during kernel upgrades.
emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl);
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID];
}
}
pragma solidity 0.4.24;
import "../evmscript/IEVMScriptExecutor.sol";
import "../evmscript/EVMScriptRegistry.sol";
import "../evmscript/executors/CallsScript.sol";
import "../kernel/Kernel.sol";
import "../acl/ACL.sol";
contract EVMScriptRegistryFactory is EVMScriptRegistryConstants {
EVMScriptRegistry public baseReg;
IEVMScriptExecutor public baseCallScript;
/**
* @notice Create a new EVMScriptRegistryFactory.
*/
constructor() public {
baseReg = new EVMScriptRegistry();
baseCallScript = IEVMScriptExecutor(new CallsScript());
}
/**
* @notice Install a new pinned instance of EVMScriptRegistry on `_dao`.
* @param _dao Kernel
* @return Installed EVMScriptRegistry
*/
function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) {
bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector);
reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true));
ACL acl = ACL(_dao.acl());
acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this);
reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript
// Clean up the permissions
acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
return reg;
}
}
pragma solidity 0.4.24;
import "../apps/AragonApp.sol";
import "./ScriptHelpers.sol";
import "./IEVMScriptExecutor.sol";
import "./IEVMScriptRegistry.sol";
/* solium-disable function-order */
// Allow public initialize() to be first
contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE");
*/
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2;
// WARN: Manager can censor all votes and the like happening in an org
bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3;
uint256 internal constant SCRIPT_START_LOCATION = 4;
string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR";
string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED";
string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED";
string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT";
struct ExecutorEntry {
IEVMScriptExecutor executor;
bool enabled;
}
uint256 private executorsNextIndex;
mapping (uint256 => ExecutorEntry) public executors;
event EnableExecutor(uint256 indexed executorId, address indexed executorAddress);
event DisableExecutor(uint256 indexed executorId, address indexed executorAddress);
modifier executorExists(uint256 _executorId) {
require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR);
_;
}
/**
* @notice Initialize the registry
*/
function initialize() public onlyInit {
initialized();
// Create empty record to begin executor IDs at 1
executorsNextIndex = 1;
}
/**
* @notice Add a new script executor with address `_executor` to the registry
* @param _executor Address of the IEVMScriptExecutor that will be added to the registry
* @return id Identifier of the executor in the registry
*/
function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) {
uint256 executorId = executorsNextIndex++;
executors[executorId] = ExecutorEntry(_executor, true);
emit EnableExecutor(executorId, _executor);
return executorId;
}
/**
* @notice Disable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function disableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
{
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage executorEntry = executors[_executorId];
require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED);
executorEntry.enabled = false;
emit DisableExecutor(_executorId, executorEntry.executor);
}
/**
* @notice Enable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function enableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
executorExists(_executorId)
{
ExecutorEntry storage executorEntry = executors[_executorId];
require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED);
executorEntry.enabled = true;
emit EnableExecutor(_executorId, executorEntry.executor);
}
/**
* @dev Get the script executor that can execute a particular script based on its first 4 bytes
* @param _script EVMScript being inspected
*/
function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT);
uint256 id = _script.getSpecId();
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage entry = executors[id];
return entry.enabled ? entry.executor : IEVMScriptExecutor(0);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
library ScriptHelpers {
function getSpecId(bytes _script) internal pure returns (uint32) {
return uint32At(_script, 0);
}
function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
0x1000000000000000000000000)
}
}
function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
0x100000000000000000000000000000000000000000000000000000000)
}
}
function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := add(_data, add(0x20, _location))
}
}
function toBytes(bytes4 _sig) internal pure returns (bytes) {
bytes memory payload = new bytes(4);
assembly { mstore(add(payload, 0x20), _sig) }
return payload;
}
}
pragma solidity 0.4.24;
// Inspired by https://github.com/reverendus/tx-manager
import "../ScriptHelpers.sol";
import "./BaseEVMScriptExecutor.sol";
contract CallsScript is BaseEVMScriptExecutor {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT");
*/
bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302;
string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL";
string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH";
/* This is manually crafted in assembly
string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED";
*/
event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
/**
* @notice Executes a number of call scripts
* @param _script [ specId (uint32) ] many calls with this structure ->
* [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
* @param _blacklist Addresses the script cannot call to, or will revert.
* @return Always returns empty byte array
*/
function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) {
uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
while (location < _script.length) {
// Check there's at least address + calldataLength available
require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH);
address contractAddress = _script.addressAt(location);
// Check address being called is not blacklist
for (uint256 i = 0; i < _blacklist.length; i++) {
require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL);
}
// logged before execution to ensure event ordering in receipt
// if failed entire execution is reverted regardless
emit LogScriptCall(msg.sender, address(this), contractAddress);
uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
uint256 startOffset = location + 0x14 + 0x04;
uint256 calldataStart = _script.locationOf(startOffset);
// compute end of script / next location
location = startOffset + calldataLength;
require(location <= _script.length, ERROR_INVALID_LENGTH);
bool success;
assembly {
success := call(
sub(gas, 5000), // forward gas left - 5000
contractAddress, // address
0, // no value
calldataStart, // calldata start
calldataLength, // calldata length
0, // don't write output
0 // don't write output
)
switch success
case 0 {
let ptr := mload(0x40)
switch returndatasize
case 0 {
// No error data was returned, revert with "EVMCALLS_CALL_REVERTED"
// See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in
// this memory layout
mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length
mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason
revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Forward the full error data
returndatacopy(ptr, 0, returndatasize)
revert(ptr, returndatasize)
}
}
default { }
}
}
// No need to allocate empty bytes for the return as this can only be called via an delegatecall
// (due to the isInitialized modifier)
}
function executorType() external pure returns (bytes32) {
return EXECUTOR_TYPE;
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../../common/Autopetrified.sol";
import "../IEVMScriptExecutor.sol";
contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified {
uint256 internal constant SCRIPT_START_LOCATION = 4;
}
pragma solidity 0.4.24;
import "../apm/APMRegistry.sol";
import "../apm/Repo.sol";
import "../ens/ENSSubdomainRegistrar.sol";
import "./DAOFactory.sol";
import "./ENSFactory.sol";
import "./AppProxyFactory.sol";
contract APMRegistryFactory is APMInternalAppNames {
DAOFactory public daoFactory;
APMRegistry public registryBase;
Repo public repoBase;
ENSSubdomainRegistrar public ensSubdomainRegistrarBase;
ENS public ens;
event DeployAPM(bytes32 indexed node, address apm);
/**
* @notice Create a new factory for deploying Aragon Package Managers (aragonPM)
* @dev Requires either a given ENS registrar or ENSFactory (used for generating a new ENS in test environments).
* @param _daoFactory Base factory for deploying DAOs
* @param _registryBase APMRegistry base contract location
* @param _repoBase Repo base contract location
* @param _ensSubBase ENSSubdomainRegistrar base contract location
* @param _ens ENS instance
* @param _ensFactory ENSFactory (used to generated a new ENS if no ENS is given)
*/
constructor(
DAOFactory _daoFactory,
APMRegistry _registryBase,
Repo _repoBase,
ENSSubdomainRegistrar _ensSubBase,
ENS _ens,
ENSFactory _ensFactory
) public // DAO initialized without evmscript run support
{
daoFactory = _daoFactory;
registryBase = _registryBase;
repoBase = _repoBase;
ensSubdomainRegistrarBase = _ensSubBase;
// Either the ENS address provided is used, if any.
// Or we use the ENSFactory to generate a test instance of ENS
// If not the ENS address nor factory address are provided, this will revert
ens = _ens != address(0) ? _ens : _ensFactory.newENS(this);
}
/**
* @notice Create a new Aragon Package Manager (aragonPM) DAO, holding the `_label` subdomain from parent `_tld` and controlled by `_root`
* @param _tld The parent node of the controlled subdomain
* @param _label The subdomain label
* @param _root Manager for the new aragonPM DAO
* @return The new aragonPM's APMRegistry app
*/
function newAPM(bytes32 _tld, bytes32 _label, address _root) public returns (APMRegistry) {
bytes32 node = keccak256(abi.encodePacked(_tld, _label));
// Assume it is the test ENS
if (ens.owner(node) != address(this)) {
// If we weren't in test ens and factory doesn't have ownership, will fail
require(ens.owner(_tld) == address(this));
ens.setSubnodeOwner(_tld, _label, this);
}
Kernel dao = daoFactory.newDAO(this);
ACL acl = ACL(dao.acl());
acl.createPermission(this, dao, dao.APP_MANAGER_ROLE(), this);
// Deploy app proxies
bytes memory noInit = new bytes(0);
ENSSubdomainRegistrar ensSub = ENSSubdomainRegistrar(
dao.newAppInstance(
keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(ENS_SUB_APP_NAME)))),
ensSubdomainRegistrarBase,
noInit,
false
)
);
APMRegistry apm = APMRegistry(
dao.newAppInstance(
keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(APM_APP_NAME)))),
registryBase,
noInit,
false
)
);
// APMRegistry controls Repos
bytes32 repoAppId = keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(REPO_APP_NAME))));
dao.setApp(dao.APP_BASES_NAMESPACE(), repoAppId, repoBase);
emit DeployAPM(node, apm);
// Grant permissions needed for APM on ENSSubdomainRegistrar
acl.createPermission(apm, ensSub, ensSub.CREATE_NAME_ROLE(), _root);
acl.createPermission(apm, ensSub, ensSub.POINT_ROOTNODE_ROLE(), _root);
// allow apm to create permissions for Repos in Kernel
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
acl.grantPermission(apm, acl, permRole);
// Initialize
ens.setOwner(node, ensSub);
ensSub.initialize(ens, node);
apm.initialize(ensSub);
uint16[3] memory firstVersion;
firstVersion[0] = 1;
acl.createPermission(this, apm, apm.CREATE_REPO_ROLE(), this);
apm.newRepoWithVersion(APM_APP_NAME, _root, firstVersion, registryBase, b("ipfs:apm"));
apm.newRepoWithVersion(ENS_SUB_APP_NAME, _root, firstVersion, ensSubdomainRegistrarBase, b("ipfs:enssub"));
apm.newRepoWithVersion(REPO_APP_NAME, _root, firstVersion, repoBase, b("ipfs:repo"));
configureAPMPermissions(acl, apm, _root);
// Permission transition to _root
acl.setPermissionManager(_root, dao, dao.APP_MANAGER_ROLE());
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
return apm;
}
function b(string memory x) internal pure returns (bytes memory y) {
y = bytes(x);
}
// Factory can be subclassed and permissions changed
function configureAPMPermissions(ACL _acl, APMRegistry _apm, address _root) internal {
_acl.grantPermission(_root, _apm, _apm.CREATE_REPO_ROLE());
_acl.setPermissionManager(_root, _apm, _apm.CREATE_REPO_ROLE());
}
}
pragma solidity 0.4.24;
import "../lib/ens/AbstractENS.sol";
import "../ens/ENSSubdomainRegistrar.sol";
import "../factory/AppProxyFactory.sol";
import "../apps/AragonApp.sol";
import "../acl/ACL.sol";
import "./Repo.sol";
contract APMInternalAppNames {
string internal constant APM_APP_NAME = "apm-registry";
string internal constant REPO_APP_NAME = "apm-repo";
string internal constant ENS_SUB_APP_NAME = "apm-enssub";
}
contract APMRegistry is AragonApp, AppProxyFactory, APMInternalAppNames {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_REPO_ROLE = keccak256("CREATE_REPO_ROLE");
*/
bytes32 public constant CREATE_REPO_ROLE = 0x2a9494d64846c9fdbf0158785aa330d8bc9caf45af27fa0e8898eb4d55adcea6;
string private constant ERROR_INIT_PERMISSIONS = "APMREG_INIT_PERMISSIONS";
string private constant ERROR_EMPTY_NAME = "APMREG_EMPTY_NAME";
AbstractENS public ens;
ENSSubdomainRegistrar public registrar;
event NewRepo(bytes32 id, string name, address repo);
/**
* NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar
* @dev Initialize can only be called once. It saves the block number in which it was initialized
* @notice Initialize this APMRegistry instance and set `_registrar` as the ENS subdomain registrar
* @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership
*/
function initialize(ENSSubdomainRegistrar _registrar) public onlyInit {
initialized();
registrar = _registrar;
ens = registrar.ens();
registrar.pointRootNode(this);
// Check APM has all permissions it needss
ACL acl = ACL(kernel().acl());
require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()), ERROR_INIT_PERMISSIONS);
require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()), ERROR_INIT_PERMISSIONS);
}
/**
* @notice Create new repo in registry with `_name`
* @param _name Repo name, must be ununsed
* @param _dev Address that will be given permission to create versions
*/
function newRepo(string _name, address _dev) public auth(CREATE_REPO_ROLE) returns (Repo) {
return _newRepo(_name, _dev);
}
/**
* @notice Create new repo in registry with `_name` and publish a first version with contract `_contractAddress` and content `@fromHex(_contentURI)`
* @param _name Repo name
* @param _dev Address that will be given permission to create versions
* @param _initialSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newRepoWithVersion(
string _name,
address _dev,
uint16[3] _initialSemanticVersion,
address _contractAddress,
bytes _contentURI
) public auth(CREATE_REPO_ROLE) returns (Repo)
{
Repo repo = _newRepo(_name, this); // need to have permissions to create version
repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI);
// Give permissions to _dev
ACL acl = ACL(kernel().acl());
acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE());
acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE());
acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE());
return repo;
}
function _newRepo(string _name, address _dev) internal returns (Repo) {
require(bytes(_name).length > 0, ERROR_EMPTY_NAME);
Repo repo = newClonedRepo();
ACL(kernel().acl()).createPermission(_dev, repo, repo.CREATE_VERSION_ROLE(), _dev);
// Creates [name] subdomain in the rootNode and sets registry as resolver
// This will fail if repo name already exists
bytes32 node = registrar.createNameAndPoint(keccak256(abi.encodePacked(_name)), repo);
emit NewRepo(node, _name, repo);
return repo;
}
function newClonedRepo() internal returns (Repo repo) {
repo = Repo(newAppProxy(kernel(), repoAppId()));
repo.initialize();
}
function repoAppId() internal view returns (bytes32) {
return keccak256(abi.encodePacked(registrar.rootNode(), keccak256(abi.encodePacked(REPO_APP_NAME))));
}
}
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol
pragma solidity ^0.4.15;
interface AbstractENS {
function owner(bytes32 _node) public constant returns (address);
function resolver(bytes32 _node) public constant returns (address);
function ttl(bytes32 _node) public constant returns (uint64);
function setOwner(bytes32 _node, address _owner) public;
function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public;
function setResolver(bytes32 _node, address _resolver) public;
function setTTL(bytes32 _node, uint64 _ttl) public;
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed _node, address _owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed _node, address _resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed _node, uint64 _ttl);
}
pragma solidity 0.4.24;
import "../lib/ens/AbstractENS.sol";
import "../lib/ens/PublicResolver.sol";
import "./ENSConstants.sol";
import "../apps/AragonApp.sol";
/* solium-disable function-order */
// Allow public initialize() to be first
contract ENSSubdomainRegistrar is AragonApp, ENSConstants {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_NAME_ROLE = keccak256("CREATE_NAME_ROLE");
bytes32 public constant DELETE_NAME_ROLE = keccak256("DELETE_NAME_ROLE");
bytes32 public constant POINT_ROOTNODE_ROLE = keccak256("POINT_ROOTNODE_ROLE");
*/
bytes32 public constant CREATE_NAME_ROLE = 0xf86bc2abe0919ab91ef714b2bec7c148d94f61fdb069b91a6cfe9ecdee1799ba;
bytes32 public constant DELETE_NAME_ROLE = 0x03d74c8724218ad4a99859bcb2d846d39999449fd18013dd8d69096627e68622;
bytes32 public constant POINT_ROOTNODE_ROLE = 0x9ecd0e7bddb2e241c41b595a436c4ea4fd33c9fa0caa8056acf084fc3aa3bfbe;
string private constant ERROR_NO_NODE_OWNERSHIP = "ENSSUB_NO_NODE_OWNERSHIP";
string private constant ERROR_NAME_EXISTS = "ENSSUB_NAME_EXISTS";
string private constant ERROR_NAME_DOESNT_EXIST = "ENSSUB_DOESNT_EXIST";
AbstractENS public ens;
bytes32 public rootNode;
event NewName(bytes32 indexed node, bytes32 indexed label);
event DeleteName(bytes32 indexed node, bytes32 indexed label);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized. This contract must be the owner of the `_rootNode` node so that it can create subdomains.
* @notice Initialize this ENSSubdomainRegistrar instance with `_ens` as the root ENS registry and `_rootNode` as the node to allocate subdomains under
* @param _ens Address of ENS registry
* @param _rootNode Node to allocate subdomains under
*/
function initialize(AbstractENS _ens, bytes32 _rootNode) public onlyInit {
initialized();
// We need ownership to create subnodes
require(_ens.owner(_rootNode) == address(this), ERROR_NO_NODE_OWNERSHIP);
ens = _ens;
rootNode = _rootNode;
}
/**
* @notice Create a new ENS subdomain record for `_label` and assign ownership to `_owner`
* @param _label Label of new subdomain
* @param _owner Owner of new subdomain
* @return node Hash of created node
*/
function createName(bytes32 _label, address _owner) external auth(CREATE_NAME_ROLE) returns (bytes32 node) {
return _createName(_label, _owner);
}
/**
* @notice Create a new ENS subdomain record for `_label` that resolves to `_target` and is owned by this ENSSubdomainRegistrar
* @param _label Label of new subdomain
* @param _target Ethereum address this new subdomain label will point to
* @return node Hash of created node
*/
function createNameAndPoint(bytes32 _label, address _target) external auth(CREATE_NAME_ROLE) returns (bytes32 node) {
node = _createName(_label, this);
_pointToResolverAndResolve(node, _target);
}
/**
* @notice Deregister ENS subdomain record for `_label`
* @param _label Label of subdomain to deregister
*/
function deleteName(bytes32 _label) external auth(DELETE_NAME_ROLE) {
bytes32 node = getNodeForLabel(_label);
address currentOwner = ens.owner(node);
require(currentOwner != address(0), ERROR_NAME_DOESNT_EXIST); // fail if deleting unset name
if (currentOwner != address(this)) { // needs to reclaim ownership so it can set resolver
ens.setSubnodeOwner(rootNode, _label, this);
}
ens.setResolver(node, address(0)); // remove resolver so it ends resolving
ens.setOwner(node, address(0));
emit DeleteName(node, _label);
}
/**
* @notice Resolve this ENSSubdomainRegistrar's root node to `_target`
* @param _target Ethereum address root node will point to
*/
function pointRootNode(address _target) external auth(POINT_ROOTNODE_ROLE) {
_pointToResolverAndResolve(rootNode, _target);
}
function _createName(bytes32 _label, address _owner) internal returns (bytes32 node) {
node = getNodeForLabel(_label);
require(ens.owner(node) == address(0), ERROR_NAME_EXISTS); // avoid name reset
ens.setSubnodeOwner(rootNode, _label, _owner);
emit NewName(node, _label);
return node;
}
function _pointToResolverAndResolve(bytes32 _node, address _target) internal {
address publicResolver = getAddr(PUBLIC_RESOLVER_NODE);
ens.setResolver(_node, publicResolver);
PublicResolver(publicResolver).setAddr(_node, _target);
}
function getAddr(bytes32 node) internal view returns (address) {
address resolver = ens.resolver(node);
return PublicResolver(resolver).addr(node);
}
function getNodeForLabel(bytes32 _label) internal view returns (bytes32) {
return keccak256(abi.encodePacked(rootNode, _label));
}
}
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol
pragma solidity ^0.4.0;
import "./AbstractENS.sol";
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
}
AbstractENS ens;
mapping(bytes32=>Record) records;
modifier only_owner(bytes32 node) {
if (ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) public {
ens = ensAddr;
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public constant returns (address ret) {
ret = records[node].addr;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) public {
records[node].addr = addr;
AddrChanged(node, addr);
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) public constant returns (bytes32 ret) {
ret = records[node].content;
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) public {
records[node].content = hash;
ContentChanged(node, hash);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) public constant returns (string ret) {
ret = records[node].name;
}
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string name) only_owner(node) public {
records[node].name = name;
NameChanged(node, name);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) {
var record = records[node];
for(contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public {
// Content types must be powers of 2
if (((contentType - 1) & contentType) != 0) throw;
records[node].abis[contentType] = data;
ABIChanged(node, contentType);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public {
records[node].pubkey = PublicKey(x, y);
PubkeyChanged(node, x, y);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string key) public constant returns (string ret) {
ret = records[node].text[key];
}
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string key, string value) only_owner(node) public {
records[node].text[key] = value;
TextChanged(node, key, key);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ENSConstants {
/* Hardcoded constants to save gas
bytes32 internal constant ENS_ROOT = bytes32(0);
bytes32 internal constant ETH_TLD_LABEL = keccak256("eth");
bytes32 internal constant ETH_TLD_NODE = keccak256(abi.encodePacked(ENS_ROOT, ETH_TLD_LABEL));
bytes32 internal constant PUBLIC_RESOLVER_LABEL = keccak256("resolver");
bytes32 internal constant PUBLIC_RESOLVER_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL));
*/
bytes32 internal constant ENS_ROOT = bytes32(0);
bytes32 internal constant ETH_TLD_LABEL = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0;
bytes32 internal constant ETH_TLD_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae;
bytes32 internal constant PUBLIC_RESOLVER_LABEL = 0x329539a1d23af1810c48a07fe7fc66a3b34fbc8b37e9b3cdb97bb88ceab7e4bf;
bytes32 internal constant PUBLIC_RESOLVER_NODE = 0xfdd5d5de6dd63db72bbc2d487944ba13bf775b50a80805fe6fcaba9b0fba88f5;
}
pragma solidity 0.4.24;
import "../apps/AragonApp.sol";
/* solium-disable function-order */
// Allow public initialize() to be first
contract Repo is AragonApp {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE");
*/
bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8;
string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP";
string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION";
string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION";
struct Version {
uint16[3] semanticVersion;
address contractAddress;
bytes contentURI;
}
uint256 internal versionsNextIndex;
mapping (uint256 => Version) internal versions;
mapping (bytes32 => uint256) internal versionIdForSemantic;
mapping (address => uint256) internal latestVersionIdForContract;
event NewVersion(uint256 versionId, uint16[3] semanticVersion);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this Repo
*/
function initialize() public onlyInit {
initialized();
versionsNextIndex = 1;
}
/**
* @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)`
* @param _newSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newVersion(
uint16[3] _newSemanticVersion,
address _contractAddress,
bytes _contentURI
) public auth(CREATE_VERSION_ROLE)
{
address contractAddress = _contractAddress;
uint256 lastVersionIndex = versionsNextIndex - 1;
uint16[3] memory lastSematicVersion;
if (lastVersionIndex > 0) {
Version storage lastVersion = versions[lastVersionIndex];
lastSematicVersion = lastVersion.semanticVersion;
if (contractAddress == address(0)) {
contractAddress = lastVersion.contractAddress;
}
// Only allows smart contract change on major version bumps
require(
lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0],
ERROR_INVALID_VERSION
);
}
require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP);
uint256 versionId = versionsNextIndex++;
versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI);
versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;
latestVersionIdForContract[contractAddress] = versionId;
emit NewVersion(versionId, _newSemanticVersion);
}
function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(versionsNextIndex - 1);
}
function getLatestForContractAddress(address _contractAddress)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(latestVersionIdForContract[_contractAddress]);
}
function getBySemanticVersion(uint16[3] _semanticVersion)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]);
}
function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION);
Version storage version = versions[_versionId];
return (version.semanticVersion, version.contractAddress, version.contentURI);
}
function getVersionsCount() public view returns (uint256) {
return versionsNextIndex - 1;
}
function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) {
bool hasBumped;
uint i = 0;
while (i < 3) {
if (hasBumped) {
if (_newVersion[i] != 0) {
return false;
}
} else if (_newVersion[i] != _oldVersion[i]) {
if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) {
return false;
}
hasBumped = true;
}
i++;
}
return hasBumped;
}
function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(version[0], version[1], version[2]));
}
}
pragma solidity 0.4.24;
import "../lib/ens/ENS.sol";
import "../lib/ens/PublicResolver.sol";
import "../ens/ENSConstants.sol";
// WARNING: This is an incredibly trustful ENS deployment, do NOT use in production!
// This contract is NOT meant to be deployed to a live network.
// Its only purpose is to easily create ENS instances for testing aragonPM.
contract ENSFactory is ENSConstants {
event DeployENS(address ens);
/**
* @notice Create a new ENS and set `_owner` as the owner of the top level domain.
* @param _owner Owner of .eth
* @return ENS
*/
function newENS(address _owner) public returns (ENS) {
ENS ens = new ENS();
// Setup .eth TLD
ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this);
// Setup public resolver
PublicResolver resolver = new PublicResolver(ens);
ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL, this);
ens.setResolver(PUBLIC_RESOLVER_NODE, resolver);
resolver.setAddr(PUBLIC_RESOLVER_NODE, resolver);
ens.setOwner(ETH_TLD_NODE, _owner);
ens.setOwner(ENS_ROOT, _owner);
emit DeployENS(ens);
return ens;
}
}
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol
pragma solidity ^0.4.0;
import "./AbstractENS.sol";
/**
* The ENS registry contract.
*/
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if (records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() public {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) public constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) public constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) public constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) public {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode keccak256(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public {
var subnode = keccak256(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) public {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) public {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
// Modified from https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/StandardToken.sol
pragma solidity 0.4.24;
import "@aragon/os/contracts/lib/math/SafeMath.sol";
contract TokenMock {
using SafeMath for uint256;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
uint256 private totalSupply_;
bool private allowTransfer_;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
// Allow us to set the inital balance for an account on construction
constructor(address initialAccount, uint256 initialBalance) public {
balances[initialAccount] = initialBalance;
totalSupply_ = initialBalance;
allowTransfer_ = true;
}
function totalSupply() public view returns (uint256) { return totalSupply_; }
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Set whether the token is transferable or not
* @param _allowTransfer Should token be transferable
*/
function setAllowTransfer(bool _allowTransfer) public {
allowTransfer_ = _allowTransfer;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(allowTransfer_);
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// Assume we want to protect for the race condition
require(allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(allowTransfer_);
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
}
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @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, ERROR_MUL_OVERFLOW);
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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW);
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, ERROR_ADD_OVERFLOW);
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, ERROR_DIV_ZERO);
return a % b;
}
}
pragma solidity ^0.4.24;
import "@aragon/os/contracts/lib/math/SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard 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 {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 internal supply;
string public name;
string public symbol;
uint8 public decimals;
constructor(
string _name,
string _symbol,
uint8 _decimals,
uint256 _totalSupply
) public {
supply = _totalSupply; // Update total supply
name = _name; // Set the id for reference
symbol = _symbol;
decimals = _decimals;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply); // Transfer event indicating token creation
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return supply;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity 0.4.24;
import "@1hive/apps-dandelion-voting/contracts/DandelionVoting.sol";
// NOTE: used because truffle does not support function overloading
contract VotingMock is DandelionVoting {
function newVoteExt(
bytes _executionScript,
string _metadata,
bool _castVote
) external returns (uint256) {
return _newVote(_executionScript, _metadata, _castVote);
}
}
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/common/IForwarder.sol";
import "@aragon/os/contracts/acl/IACLOracle.sol";
import "@aragon/os/contracts/lib/math/SafeMath.sol";
import "@aragon/os/contracts/lib/math/SafeMath64.sol";
import "@aragon/apps-shared-minime/contracts/MiniMeToken.sol";
contract DandelionVoting is IForwarder, IACLOracle, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE");
bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE");
bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE");
bytes32 public constant MODIFY_BUFFER_BLOCKS_ROLE = keccak256("MODIFY_BUFFER_BLOCKS_ROLE");
bytes32 public constant MODIFY_EXECUTION_DELAY_ROLE = keccak256("MODIFY_EXECUTION_DELAY_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
uint8 private constant EXECUTION_PERIOD_FALLBACK_DIVISOR = 2;
string private constant ERROR_VOTE_ID_ZERO = "DANDELION_VOTING_VOTE_ID_ZERO";
string private constant ERROR_NO_VOTE = "DANDELION_VOTING_NO_VOTE";
string private constant ERROR_INIT_PCTS = "DANDELION_VOTING_INIT_PCTS";
string private constant ERROR_CHANGE_SUPPORT_PCTS = "DANDELION_VOTING_CHANGE_SUPPORT_PCTS";
string private constant ERROR_CHANGE_QUORUM_PCTS = "DANDELION_VOTING_CHANGE_QUORUM_PCTS";
string private constant ERROR_INIT_SUPPORT_TOO_BIG = "DANDELION_VOTING_INIT_SUPPORT_TOO_BIG";
string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "DANDELION_VOTING_CHANGE_SUPP_TOO_BIG";
string private constant ERROR_CAN_NOT_VOTE = "DANDELION_VOTING_CAN_NOT_VOTE";
string private constant ERROR_CAN_NOT_EXECUTE = "DANDELION_VOTING_CAN_NOT_EXECUTE";
string private constant ERROR_CAN_NOT_FORWARD = "DANDELION_VOTING_CAN_NOT_FORWARD";
string private constant ERROR_ORACLE_SENDER_MISSING = "DANDELION_VOTING_ORACLE_SENDER_MISSING";
string private constant ERROR_ORACLE_SENDER_TOO_BIG = "DANDELION_VOTING_ORACLE_SENDER_TOO_BIG";
string private constant ERROR_ORACLE_SENDER_ZERO = "DANDELION_VOTING_ORACLE_SENDER_ZERO";
enum VoterState { Absent, Yea, Nay }
struct Vote {
bool executed;
uint64 startBlock;
uint64 executionBlock;
uint64 snapshotBlock;
uint64 supportRequiredPct;
uint64 minAcceptQuorumPct;
uint256 yea;
uint256 nay;
bytes executionScript;
mapping (address => VoterState) voters;
}
MiniMeToken public token;
uint64 public supportRequiredPct;
uint64 public minAcceptQuorumPct;
uint64 public durationBlocks;
uint64 public bufferBlocks;
uint64 public executionDelayBlocks;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => Vote) internal votes;
uint256 public votesLength;
mapping (address => uint256) public latestYeaVoteId;
event StartVote(uint256 indexed voteId, address indexed creator, string metadata);
event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake);
event ExecuteVote(uint256 indexed voteId);
event ChangeSupportRequired(uint64 supportRequiredPct);
event ChangeMinQuorum(uint64 minAcceptQuorumPct);
event ChangeBufferBlocks(uint64 bufferBlocks);
event ChangeExecutionDelayBlocks(uint64 executionDelayBlocks);
modifier voteExists(uint256 _voteId) {
require(_voteId != 0, ERROR_VOTE_ID_ZERO);
require(_voteId <= votesLength, ERROR_NO_VOTE);
_;
}
/**
* @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, a voting duration of `_voteDurationBlocks` blocks, and a vote buffer of `_voteBufferBlocks` blocks
* @param _token MiniMeToken Address that will be used as governance token
* @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _durationBlocks Blocks that a vote will be open for token holders to vote
* @param _bufferBlocks Minimum number of blocks between the start block of each vote
* @param _executionDelayBlocks Minimum number of blocks between the end of a vote and when it can be executed
*/
function initialize(
MiniMeToken _token,
uint64 _supportRequiredPct,
uint64 _minAcceptQuorumPct,
uint64 _durationBlocks,
uint64 _bufferBlocks,
uint64 _executionDelayBlocks
)
external
onlyInit
{
initialized();
require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG);
token = _token;
supportRequiredPct = _supportRequiredPct;
minAcceptQuorumPct = _minAcceptQuorumPct;
durationBlocks = _durationBlocks;
bufferBlocks = _bufferBlocks;
executionDelayBlocks = _executionDelayBlocks;
}
/**
* @notice Change required support to `@formatPct(_supportRequiredPct)`%
* @param _supportRequiredPct New required support
*/
function changeSupportRequiredPct(uint64 _supportRequiredPct)
external
authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct)))
{
require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG);
supportRequiredPct = _supportRequiredPct;
emit ChangeSupportRequired(_supportRequiredPct);
}
/**
* @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`%
* @param _minAcceptQuorumPct New acceptance quorum
*/
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct)
external
authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct)))
{
require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS);
minAcceptQuorumPct = _minAcceptQuorumPct;
emit ChangeMinQuorum(_minAcceptQuorumPct);
}
/**
* @notice Change vote buffer to `_voteBufferBlocks` blocks
* @param _bufferBlocks New vote buffer defined in blocks
*/
function changeBufferBlocks(uint64 _bufferBlocks) external auth(MODIFY_BUFFER_BLOCKS_ROLE) {
bufferBlocks = _bufferBlocks;
emit ChangeBufferBlocks(_bufferBlocks);
}
/**
* @notice Change execution delay to `_executionDelayBlocks` blocks
* @param _executionDelayBlocks New vote execution delay defined in blocks
*/
function changeExecutionDelayBlocks(uint64 _executionDelayBlocks) external auth(MODIFY_EXECUTION_DELAY_ROLE) {
executionDelayBlocks = _executionDelayBlocks;
emit ChangeExecutionDelayBlocks(_executionDelayBlocks);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @param _castVote Whether to also cast newly created vote
* @return voteId id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata, bool _castVote)
external
auth(CREATE_VOTES_ROLE)
returns (uint256 voteId)
{
return _newVote(_executionScript, _metadata, _castVote);
}
/**
* @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
* @param _supports Whether voter supports the vote
*/
function vote(uint256 _voteId, bool _supports) external voteExists(_voteId) {
require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE);
_vote(_voteId, _supports, msg.sender);
}
/**
* @notice Execute vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
*/
function executeVote(uint256 _voteId) external {
require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE);
Vote storage vote_ = votes[_voteId];
vote_.executed = true;
bytes memory input = new bytes(0); // TODO: Consider input for voting scripts
runScript(vote_.executionScript, input, new address[](0));
emit ExecuteVote(_voteId);
}
// Forwarding fns
/**
* @notice Returns whether the Voting app is a forwarder or not
* @dev IForwarder interface conformance
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Creates a vote to execute the desired action, and casts a support vote if possible
* @dev IForwarder interface conformance
* @param _evmScript Start vote with script
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
_newVote(_evmScript, "", true);
}
/**
* @notice Returns whether `_sender` can forward actions or not
* @dev IForwarder interface conformance
* @param _sender Address of the account intending to forward an action
* @return True if the given address can create votes, false otherwise
*/
function canForward(address _sender, bytes) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, CREATE_VOTES_ROLE, arr());
}
// ACL Oracle fns
/**
* @notice Returns whether the sender has voted on the most recent open vote or closed unexecuted vote.
* @dev IACLOracle interface conformance. The ACLOracle permissioned function should specify the sender
* with 'authP(SOME_ACL_ROLE, arr(sender))', where sender is typically set to 'msg.sender'.
* @param _how Array passed by Kernel when using 'authP()'. First item should be the address to check can perform.
* return False if the sender has voted on the most recent open vote or closed unexecuted vote, true if they haven't.
*/
function canPerform(address, address, bytes32, uint256[] _how) external view returns (bool) {
if (votesLength == 0) {
return true;
}
require(_how.length > 0, ERROR_ORACLE_SENDER_MISSING);
require(_how[0] < 2**160, ERROR_ORACLE_SENDER_TOO_BIG);
require(_how[0] != 0, ERROR_ORACLE_SENDER_ZERO);
address sender = address(_how[0]);
uint256 senderLatestYeaVoteId = latestYeaVoteId[sender];
Vote storage senderLatestYeaVote_ = votes[senderLatestYeaVoteId];
uint64 blockNumber = getBlockNumber64();
bool senderLatestYeaVoteFailed = !_votePassed(senderLatestYeaVote_);
bool senderLatestYeaVoteExecutionBlockPassed = blockNumber >= senderLatestYeaVote_.executionBlock;
uint64 fallbackPeriodLength = bufferBlocks / EXECUTION_PERIOD_FALLBACK_DIVISOR;
bool senderLatestYeaVoteFallbackPeriodPassed = blockNumber > senderLatestYeaVote_.executionBlock.add(fallbackPeriodLength);
return senderLatestYeaVoteFailed && senderLatestYeaVoteExecutionBlockPassed || senderLatestYeaVote_.executed || senderLatestYeaVoteFallbackPeriodPassed;
}
// Getter fns
/**
* @notice Tells whether a vote #`_voteId` can be executed or not
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @return True if the given vote can be executed, false otherwise
*/
function canExecute(uint256 _voteId) public view returns (bool) {
return _canExecute(_voteId);
}
/**
* @notice Tells whether `_sender` can participate in the vote #`_voteId` or not
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @return True if the given voter can participate a certain vote, false otherwise
*/
function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) {
return _canVote(_voteId, _voter);
}
/**
* @dev Return all information for a vote by its ID
* @param _voteId Vote identifier
* @return Vote open status
* @return Vote executed status
* @return Vote start block
* @return Vote snapshot block
* @return Vote support required
* @return Vote minimum acceptance quorum
* @return Vote yeas amount
* @return Vote nays amount
* @return Vote power
* @return Vote script
*/
function getVote(uint256 _voteId)
public
view
voteExists(_voteId)
returns (
bool open,
bool executed,
uint64 startBlock,
uint64 executionBlock,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 votingPower,
uint256 yea,
uint256 nay,
bytes script
)
{
Vote storage vote_ = votes[_voteId];
open = _isVoteOpen(vote_);
executed = vote_.executed;
startBlock = vote_.startBlock;
executionBlock = vote_.executionBlock;
snapshotBlock = vote_.snapshotBlock;
votingPower = token.totalSupplyAt(vote_.snapshotBlock);
supportRequired = vote_.supportRequiredPct;
minAcceptQuorum = vote_.minAcceptQuorumPct;
yea = vote_.yea;
nay = vote_.nay;
script = vote_.executionScript;
}
/**
* @dev Return the state of a voter for a given vote by its ID
* @param _voteId Vote identifier
* @return VoterState of the requested voter for a certain vote
*/
function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) {
return votes[_voteId].voters[_voter];
}
// Internal fns
/**
* @dev Internal function to create a new vote
* @return voteId id for newly created vote
*/
function _newVote(bytes _executionScript, string _metadata, bool _castVote) internal returns (uint256 voteId) {
voteId = ++votesLength; // Increment votesLength before assigning to votedId. The first voteId is 1.
uint64 previousVoteStartBlock = votes[voteId - 1].startBlock;
uint64 earliestStartBlock = previousVoteStartBlock == 0 ? 0 : previousVoteStartBlock.add(bufferBlocks);
uint64 startBlock = earliestStartBlock < getBlockNumber64() ? getBlockNumber64() : earliestStartBlock;
uint64 executionBlock = startBlock.add(durationBlocks).add(executionDelayBlocks);
Vote storage vote_ = votes[voteId];
vote_.startBlock = startBlock;
vote_.executionBlock = executionBlock;
vote_.snapshotBlock = startBlock - 1; // avoid double voting in this very block
vote_.supportRequiredPct = supportRequiredPct;
vote_.minAcceptQuorumPct = minAcceptQuorumPct;
vote_.executionScript = _executionScript;
emit StartVote(voteId, msg.sender, _metadata);
if (_castVote && _canVote(voteId, msg.sender)) {
_vote(voteId, true, msg.sender);
}
}
/**
* @dev Internal function to cast a vote. It assumes the queried vote exists.
*/
function _vote(uint256 _voteId, bool _supports, address _voter) internal {
Vote storage vote_ = votes[_voteId];
uint256 voterStake = _voterStake(vote_, _voter);
if (_supports) {
vote_.yea = vote_.yea.add(voterStake);
if (latestYeaVoteId[_voter] < _voteId) {
latestYeaVoteId[_voter] = _voteId;
}
} else {
vote_.nay = vote_.nay.add(voterStake);
}
vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay;
emit CastVote(_voteId, _voter, _supports, voterStake);
}
/**
* @dev Internal function to check if a vote can be executed. It assumes the queried vote exists.
* @return True if the given vote can be executed, false otherwise
*/
function _canExecute(uint256 _voteId) internal view voteExists(_voteId) returns (bool) {
Vote storage vote_ = votes[_voteId];
if (vote_.executed) {
return false;
}
// This will always be later than the end of the previous vote
if (getBlockNumber64() < vote_.executionBlock) {
return false;
}
return _votePassed(vote_);
}
/**
* @dev Internal function to check if a vote has passed. It assumes the vote period has passed.
* @return True if the given vote has passed, false otherwise.
*/
function _votePassed(Vote storage vote_) internal view returns (bool) {
uint256 totalVotes = vote_.yea.add(vote_.nay);
uint256 votingPowerAtSnapshot = token.totalSupplyAt(vote_.snapshotBlock);
bool hasSupportRequired = _isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct);
bool hasMinQuorum = _isValuePct(vote_.yea, votingPowerAtSnapshot, vote_.minAcceptQuorumPct);
return hasSupportRequired && hasMinQuorum;
}
/**
* @dev Internal function to check if a voter can participate on a vote. It assumes the queried vote exists.
* @return True if the given voter can participate a certain vote, false otherwise
*/
function _canVote(uint256 _voteId, address _voter) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
uint256 voterStake = _voterStake(vote_, _voter);
bool hasNotVoted = vote_.voters[_voter] == VoterState.Absent;
return _isVoteOpen(vote_) && voterStake > 0 && hasNotVoted;
}
/**
* @dev Internal function to determine a voters stake which is the minimum of snapshot balance and current balance.
* @return Voters current stake.
*/
function _voterStake(Vote storage vote_, address _voter) internal view returns (uint256) {
uint256 balanceAtSnapshot = token.balanceOfAt(_voter, vote_.snapshotBlock);
uint256 currentBalance = token.balanceOf(_voter);
return balanceAtSnapshot < currentBalance ? balanceAtSnapshot : currentBalance;
}
/**
* @dev Internal function to check if a vote is still open
* @return True if the given vote is open, false otherwise
*/
function _isVoteOpen(Vote storage vote_) internal view returns (bool) {
uint256 votingPowerAtSnapshot = token.totalSupplyAt(vote_.snapshotBlock);
uint64 blockNumber = getBlockNumber64();
return votingPowerAtSnapshot > 0 && blockNumber >= vote_.startBlock && blockNumber < vote_.startBlock.add(durationBlocks);
}
/**
* @dev Calculates whether `_value` is more than a percentage `_pct` of `_total`
*/
function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) {
if (_total == 0) {
return false;
}
uint256 computedPct = _value.mul(PCT_BASE) / _total;
return computedPct > _pct;
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IForwarder {
function isForwarder() external pure returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function canForward(address sender, bytes evmCallScript) public view returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function forward(bytes evmCallScript) public;
}
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules
// Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417
pragma solidity ^0.4.24;
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
pragma solidity ^0.4.24;
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
import "./ITokenController.sol";
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 ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.1"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = _tokenFactory;
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = _parentToken;
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount)
return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
_spender.receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), snapshot);
return cloneToken;
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController public {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) {
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () external payable {
require(isContract(controller));
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true);
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController public {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
MiniMeToken _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
pragma solidity ^0.4.24;
/// @dev The token controller contract must implement these functions
interface ITokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) external payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) external 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) external returns(bool);
}
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/common/SafeERC20.sol";
import "@aragon/os/contracts/lib/token/ERC20.sol";
import "@1hive/apps-dandelion-voting/contracts/DandelionVoting.sol";
import "@aragon/apps-vault/contracts/Vault.sol";
import "@aragon/os/contracts/lib/math/SafeMath.sol";
import "@aragon/os/contracts/lib/math/SafeMath64.sol";
import "@aragon/apps-shared-minime/contracts/MiniMeToken.sol";
contract VotingRewards is AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CHANGE_EPOCH_DURATION_ROLE = keccak256("CHANGE_EPOCH_DURATION_ROLE");
bytes32 public constant CHANGE_LOCK_TIME_ROLE = keccak256("CHANGE_LOCK_TIME_ROLE");
bytes32 public constant CHANGE_MISSING_VOTES_THRESHOLD_ROLE = keccak256("CHANGE_MISSING_VOTES_THRESHOLD_ROLE");
bytes32 public constant OPEN_REWARDS_DISTRIBUTION_ROLE = keccak256("OPEN_REWARDS_DISTRIBUTION_ROLE");
bytes32 public constant CLOSE_REWARDS_DISTRIBUTION_ROLE = keccak256("CLOSE_REWARDS_DISTRIBUTION_ROLE");
bytes32 public constant DISTRIBUTE_REWARDS_ROLE = keccak256("DISTRIBUTE_REWARDS_ROLE");
bytes32 public constant CHANGE_PERCENTAGE_REWARDS_ROLE = keccak256("CHANGE_PERCENTAGE_REWARDS_ROLE");
bytes32 public constant CHANGE_VAULT_ROLE = keccak256("CHANGE_VAULT_ROLE");
bytes32 public constant CHANGE_REWARDS_TOKEN_ROLE = keccak256("CHANGE_REWARDS_TOKEN_ROLE");
bytes32 public constant CHANGE_VOTING_ROLE = keccak256("CHANGE_VOTING_ROLE");
uint64 public constant PCT_BASE = 10**18; // 0% = 0; 1% = 10^16; 100% = 10^18
string private constant ERROR_ADDRESS_NOT_CONTRACT = "VOTING_REWARDS_ADDRESS_NOT_CONTRACT";
string private constant ERROR_EPOCH = "VOTING_REWARDS_ERROR_EPOCH";
string private constant ERROR_PERCENTAGE_REWARDS = "VOTING_REWARDS_ERROR_PERCENTAGE_REWARDS";
// prettier-ignore
string private constant ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED = "VOTING_REWARDS_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED";
// prettier-ignore
string private constant ERROR_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED = "VOTING_REWARDS_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED";
string private constant ERROR_NO_REWARDS = "VOTING_REWARDS_NO_REWARDS";
struct Reward {
uint256 amount;
uint64 lockBlock;
uint64 lockTime;
}
Vault public baseVault;
Vault public rewardsVault;
DandelionVoting public dandelionVoting;
address public rewardsToken;
uint256 public percentageRewards;
uint256 public missingVotesThreshold;
uint64 public epochDuration;
uint64 public currentEpoch;
uint64 public startBlockNumberOfCurrentEpoch;
uint64 public lockTime;
uint64 public lastRewardsDistributionBlock;
uint64 private deployBlock;
bool public isDistributionOpen;
// NOTE: previousRewardsDistributionBlockNumber kept even if not used so as not to break the proxy contract storage after an upgrade
mapping(address => uint64) private previousRewardsDistributionBlockNumber;
mapping(address => Reward[]) public addressUnlockedRewards;
mapping(address => Reward[]) public addressWithdrawnRewards; // kept even if not used so as not to break the proxy contract storage after an upgrade
event BaseVaultChanged(address baseVault);
event RewardsVaultChanged(address rewardsVault);
event DandelionVotingChanged(address dandelionVoting);
event PercentageRewardsChanged(uint256 percentageRewards);
event RewardDistributed(address indexed beneficiary, uint256 indexed amount, uint64 lockTime);
event RewardCollected(address indexed beneficiary, uint256 amount, uint64 indexed lockBlock, uint64 lockTime);
event EpochDurationChanged(uint64 epochDuration);
event MissingVoteThresholdChanged(uint256 missingVotesThreshold);
event LockTimeChanged(uint64 lockTime);
event RewardsDistributionEpochOpened(uint64 startBlock, uint64 endBlock);
event RewardsDistributionEpochClosed(uint64 rewardDistributionBlock);
event RewardsTokenChanged(address rewardsToken);
/**
* @notice Initialize VotingRewards app contract
* @param _baseVault Vault address from which token are taken
* @param _rewardsVault Vault address to which token are put
* @param _rewardsToken Accepted token address
* @param _epochDuration number of blocks for which an epoch is opened
* @param _percentageRewards percentage of a reward expressed as a number between 10^16 and 10^18
* @param _lockTime number of blocks for which token will be locked after colleting reward
* @param _missingVotesThreshold number of missing votes allowed in an epoch
*/
function initialize(
address _baseVault,
address _rewardsVault,
address _dandelionVoting,
address _rewardsToken,
uint64 _epochDuration,
uint256 _percentageRewards,
uint64 _lockTime,
uint256 _missingVotesThreshold
) external onlyInit {
require(isContract(_baseVault), ERROR_ADDRESS_NOT_CONTRACT);
require(isContract(_rewardsVault), ERROR_ADDRESS_NOT_CONTRACT);
require(isContract(_dandelionVoting), ERROR_ADDRESS_NOT_CONTRACT);
require(isContract(_rewardsToken), ERROR_ADDRESS_NOT_CONTRACT);
require(_percentageRewards <= PCT_BASE, ERROR_PERCENTAGE_REWARDS);
baseVault = Vault(_baseVault);
rewardsVault = Vault(_rewardsVault);
dandelionVoting = DandelionVoting(_dandelionVoting);
rewardsToken = _rewardsToken;
epochDuration = _epochDuration;
percentageRewards = _percentageRewards;
missingVotesThreshold = _missingVotesThreshold;
lockTime = _lockTime;
deployBlock = getBlockNumber64();
lastRewardsDistributionBlock = getBlockNumber64();
currentEpoch = 0;
initialized();
}
/**
* @notice Open the distribution for the current epoch from _fromBlock
* @param _fromBlock block from which starting to look for rewards
*/
function openRewardsDistributionForEpoch(uint64 _fromBlock) external auth(OPEN_REWARDS_DISTRIBUTION_ROLE) {
require(!isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED);
require(_fromBlock > lastRewardsDistributionBlock, ERROR_EPOCH);
require(getBlockNumber64() - lastRewardsDistributionBlock > epochDuration, ERROR_EPOCH);
startBlockNumberOfCurrentEpoch = _fromBlock;
isDistributionOpen = true;
emit RewardsDistributionEpochOpened(_fromBlock, _fromBlock + epochDuration);
}
/**
* @notice close distribution for thee current epoch if it's opened and starts a new one
*/
function closeRewardsDistributionForCurrentEpoch() external auth(CLOSE_REWARDS_DISTRIBUTION_ROLE) {
require(isDistributionOpen == true, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED);
isDistributionOpen = false;
currentEpoch = currentEpoch.add(1);
lastRewardsDistributionBlock = getBlockNumber64();
emit RewardsDistributionEpochClosed(lastRewardsDistributionBlock);
}
/**
* @notice distribute rewards for a list of address. Tokens are locked for lockTime in rewardsVault
* @param _beneficiaries address that are looking for reward
* @dev this function should be called from outside each _epochDuration seconds
*/
function distributeRewardsToMany(address[] _beneficiaries, uint256[] _amount)
external
auth(DISTRIBUTE_REWARDS_ROLE)
returns (bool)
{
require(isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED);
uint256 totalRewardAmount = 0;
for (uint256 i = 0; i < _beneficiaries.length; i++) {
// NOTE: switching to a semi-trusted solution in order to spend less in gas
// _assignUnlockedReward(_beneficiaries[i], _amount[i]);
totalRewardAmount = totalRewardAmount.add(_amount[i]);
emit RewardDistributed(_beneficiaries[i], _amount[i], lockTime);
}
baseVault.transfer(rewardsToken, rewardsVault, totalRewardAmount);
return true;
}
/**
* @notice Distribute rewards to _beneficiary
* @param _beneficiary address to which the deposit will be transferred if successful
* @dev baseVault should have TRANSFER_ROLE permission
*/
function distributeRewardsTo(address _beneficiary, uint256 _amount)
external
auth(DISTRIBUTE_REWARDS_ROLE)
returns (bool)
{
require(isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED);
// NOTE: switching to a semi-trusted solution in order to spend less in gas
// _assignUnlockedReward(_beneficiary, _amount);
baseVault.transfer(rewardsToken, rewardsVault, _amount);
emit RewardDistributed(_beneficiary, _amount, lockTime);
return true;
}
/**
* @notice collect rewards for a list of address
* if lockTime is passed since when tokens have been distributed
* @param _beneficiaries addresses that should be fund with rewards
*/
function collectRewardsForMany(address[] _beneficiaries) external {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
collectRewardsFor(_beneficiaries[i]);
}
}
/**
* @notice Change minimum number of seconds to claim dandelionVoting rewards
* @param _epochDuration number of seconds minimum to claim access to dandelionVoting rewards
*/
function changeEpochDuration(uint64 _epochDuration) external auth(CHANGE_EPOCH_DURATION_ROLE) {
require(_epochDuration > 0, ERROR_EPOCH);
epochDuration = _epochDuration;
emit EpochDurationChanged(_epochDuration);
}
/**
* @notice Change minimum number of missing votes allowed
* @param _missingVotesThreshold number of seconds minimum to claim access to voting rewards
*/
function changeMissingVotesThreshold(uint256 _missingVotesThreshold)
external
auth(CHANGE_MISSING_VOTES_THRESHOLD_ROLE)
{
missingVotesThreshold = _missingVotesThreshold;
emit MissingVoteThresholdChanged(_missingVotesThreshold);
}
/**
* @notice Change minimum number of missing votes allowed
* @param _lockTime number of seconds for which tokens will be locked after distributing reward
*/
function changeLockTime(uint64 _lockTime) external auth(CHANGE_LOCK_TIME_ROLE) {
lockTime = _lockTime;
emit LockTimeChanged(_lockTime);
}
/**
* @notice Change Base Vault
* @param _baseVault new base vault address
*/
function changeBaseVaultContractAddress(address _baseVault) external auth(CHANGE_VAULT_ROLE) {
require(isContract(_baseVault), ERROR_ADDRESS_NOT_CONTRACT);
baseVault = Vault(_baseVault);
emit BaseVaultChanged(_baseVault);
}
/**
* @notice Change Reward Vault
* @param _rewardsVault new reward vault address
*/
function changeRewardsVaultContractAddress(address _rewardsVault) external auth(CHANGE_VAULT_ROLE) {
require(isContract(_rewardsVault), ERROR_ADDRESS_NOT_CONTRACT);
rewardsVault = Vault(_rewardsVault);
emit RewardsVaultChanged(_rewardsVault);
}
/**
* @notice Change Dandelion Voting contract address
* @param _dandelionVoting new dandelionVoting address
*/
function changeDandelionVotingContractAddress(address _dandelionVoting) external auth(CHANGE_VOTING_ROLE) {
require(isContract(_dandelionVoting), ERROR_ADDRESS_NOT_CONTRACT);
dandelionVoting = DandelionVoting(_dandelionVoting);
emit DandelionVotingChanged(_dandelionVoting);
}
/**
* @notice Change percentage rewards
* @param _percentageRewards new percentage
* @dev PCT_BASE is the maximun allowed percentage
*/
function changePercentageRewards(uint256 _percentageRewards) external auth(CHANGE_PERCENTAGE_REWARDS_ROLE) {
require(_percentageRewards <= PCT_BASE, ERROR_PERCENTAGE_REWARDS);
percentageRewards = _percentageRewards;
emit PercentageRewardsChanged(percentageRewards);
}
/**
* @notice Change rewards token
* @param _rewardsToken new percentage
*/
function changeRewardsTokenContractAddress(address _rewardsToken) external auth(CHANGE_REWARDS_TOKEN_ROLE) {
require(isContract(_rewardsToken), ERROR_ADDRESS_NOT_CONTRACT);
rewardsToken = _rewardsToken;
emit RewardsTokenChanged(rewardsToken);
}
/**
* @notice Returns all unlocked rewards given an address
* @param _beneficiary address of which we want to get all rewards
*/
function getUnlockedRewardsInfo(address _beneficiary) external view returns (Reward[]) {
Reward[] storage rewards = addressUnlockedRewards[_beneficiary];
return rewards;
}
/**
* @notice Returns all withdrawan rewards given an address
* @param _beneficiary address of which we want to get all rewards
*/
function getWithdrawnRewardsInfo(address _beneficiary) external view returns (Reward[]) {
Reward[] storage rewards = addressWithdrawnRewards[_beneficiary];
return rewards;
}
/**
* @notice collect rewards for an msg.sender
*/
function collectRewards() external {
collectRewardsFor(msg.sender);
}
/**
* @notice collect rewards for an address if lockTime is passed since when tokens have been distributed
* @param _beneficiary address that should be fund with rewards
* @dev rewardsVault should have TRANSFER_ROLE permission
*/
function collectRewardsFor(address _beneficiary) public returns (bool) {
uint64 currentBlockNumber = getBlockNumber64();
Reward[] storage rewards = addressUnlockedRewards[_beneficiary];
uint256 rewardsLength = rewards.length;
require(rewardsLength > 0, ERROR_NO_REWARDS);
uint256 collectedRewardsAmount = 0;
for (uint256 i = 0; i < rewardsLength; i++) {
Reward reward = rewards[i];
if (currentBlockNumber - reward.lockBlock > reward.lockTime && !_isRewardEmpty(reward)) {
collectedRewardsAmount = collectedRewardsAmount + reward.amount;
emit RewardCollected(_beneficiary, reward.amount, reward.lockBlock, reward.lockTime);
delete rewards[i];
}
}
rewardsVault.transfer(rewardsToken, _beneficiary, collectedRewardsAmount);
return true;
}
/**
* @notice Check if msg.sender is able to be rewarded, and in positive case,
* he will be funded with the corresponding earned amount of tokens
* @param _beneficiary address to which the deposit will be transferred if successful
*/
function _assignUnlockedReward(address _beneficiary, uint256 _amount) internal returns (bool) {
Reward[] storage unlockedRewards = addressUnlockedRewards[_beneficiary];
uint64 currentBlockNumber = getBlockNumber64();
// prettier-ignore
uint64 lastBlockDistributedReward = unlockedRewards.length == 0 ? deployBlock : unlockedRewards[unlockedRewards.length - 1].lockBlock;
// NOTE: avoid double collecting for the same epoch
require(currentBlockNumber.sub(lastBlockDistributedReward) > epochDuration, ERROR_EPOCH);
addressUnlockedRewards[_beneficiary].push(Reward(_amount, currentBlockNumber, lockTime));
return true;
}
/**
* @notice Check if a Reward is empty
* @param _reward reward
*/
function _isRewardEmpty(Reward memory _reward) internal pure returns (bool) {
return _reward.amount == 0 && _reward.lockBlock == 0 && _reward.lockTime == 0;
}
}
pragma solidity 0.4.24;
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/common/DepositableStorage.sol";
import "@aragon/os/contracts/common/EtherTokenConstant.sol";
import "@aragon/os/contracts/common/SafeERC20.sol";
import "@aragon/os/contracts/lib/token/ERC20.sol";
contract Vault is EtherTokenConstant, AragonApp, DepositableStorage {
using SafeERC20 for ERC20;
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO";
string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE";
string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO";
string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO";
string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED";
string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED";
event VaultTransfer(address indexed token, address indexed to, uint256 amount);
event VaultDeposit(address indexed token, address indexed sender, uint256 amount);
/**
* @dev On a normal send() or transfer() this fallback is never executed as it will be
* intercepted by the Proxy (see aragonOS#281)
*/
function () external payable isInitialized {
require(msg.data.length == 0, ERROR_DATA_NON_ZERO);
_deposit(ETH, msg.value);
}
/**
* @notice Initialize Vault app
* @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work
*/
function initialize() external onlyInit {
initialized();
setDepositable(true);
}
/**
* @notice Deposit `_value` `_token` to the vault
* @param _token Address of the token being transferred
* @param _value Amount of tokens being transferred
*/
function deposit(address _token, uint256 _value) external payable isInitialized {
_deposit(_token, _value);
}
/**
* @notice Transfer `_value` `_token` from the Vault to `_to`
* @param _token Address of the token being transferred
* @param _to Address of the recipient of tokens
* @param _value Amount of tokens being transferred
*/
/* solium-disable-next-line function-order */
function transfer(address _token, address _to, uint256 _value)
external
authP(TRANSFER_ROLE, arr(_token, _to, _value))
{
require(_value > 0, ERROR_TRANSFER_VALUE_ZERO);
if (_token == ETH) {
require(_to.send(_value), ERROR_SEND_REVERTED);
} else {
require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED);
}
emit VaultTransfer(_token, _to, _value);
}
function balance(address _token) public view returns (uint256) {
if (_token == ETH) {
return address(this).balance;
} else {
return ERC20(_token).staticBalanceOf(address(this));
}
}
/**
* @dev Disable recovery escape hatch, as it could be used
* maliciously to transfer funds away from the vault
*/
function allowRecoverability(address) public view returns (bool) {
return false;
}
function _deposit(address _token, uint256 _value) internal {
require(isDepositable(), ERROR_NOT_DEPOSITABLE);
require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO);
if (_token == ETH) {
// Deposit is implicit in this case
require(msg.value == _value, ERROR_VALUE_MISMATCH);
} else {
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _value),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
emit VaultDeposit(_token, msg.sender, _value);
}
}
| * @dev Transfer tokens from one address to another @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _value uint256 the amount of tokens to be transferred/ | function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| 13,453,869 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
1132,
2254,
5034,
326,
3844,
434,
2430,
358,
506,
906,
4193,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
203,
565,
262,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
1132,
1648,
324,
26488,
63,
67,
2080,
19226,
203,
3639,
2583,
24899,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
19226,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
3639,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
3639,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
3626,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-02
*/
/**
*Submitted for verification at Etherscan.io on 2020-11-11
*/
/**
*Submitted for verification at Etherscan.io on 2020-02-28
*/
/**
*Submitted for verification at Etherscan.io on 2020-01-11
*/
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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
using SafeMath for uint256;
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return one ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return one wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev multiplies two wad, rounding half up to the nearest wad
* @param a wad
* @param b wad
* @return the result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
return halfWAD.add(a.mul(b)).div(WAD);
}
/**
* @dev divides two wad, rounding half up to the nearest wad
* @param a wad
* @param b wad
* @return the result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(WAD)).div(b);
}
/**
* @dev multiplies two ray, rounding half up to the nearest ray
* @param a ray
* @param b ray
* @return the result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
return halfRAY.add(a.mul(b)).div(RAY);
}
/**
* @dev divides two ray, rounding half up to the nearest ray
* @param a ray
* @param b ray
* @return the result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(RAY)).div(b);
}
/**
* @dev casts ray down to wad
* @param a ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
return halfRatio.add(a).div(WAD_RAY_RATIO);
}
/**
* @dev convert wad up to ray
* @param a wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
return a.mul(WAD_RAY_RATIO);
}
/**
* @dev calculates base^exp. The code uses the ModExp precompile
* @return base^exp, in ray
*/
//solium-disable-next-line
function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rayMul(x, x);
if (n % 2 != 0) {
z = rayMul(z, x);
}
}
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// 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, "ReentrancyGuard: reentrant call");
}
}
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
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 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.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Implementation of the `IERC20` interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using `_mint`.
* For a generic mechanism see `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
/**
* @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 that 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;
}
}
/**
* @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);
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");
}
}
}
/**
* @title VersionedInitializable
*
* @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.
*
* @author Aave, inspired by the OpenZeppelin Initializable contract
*/
contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 private lastInitializedRevision = 0;
/**
* @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() {
uint256 revision = getRevision();
require(initializing || isConstructor() || revision > lastInitializedRevision, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
lastInitializedRevision = revision;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure returns(uint256);
/// @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;
//solium-disable-next-line
assembly {
cs := extcodesize(address)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
//solium-disable-next-line
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize)
}
default {
return(0, returndatasize)
}
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @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 Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
"Cannot set a proxy implementation to a non-contract address"
);
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @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 Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) public payable UpgradeabilityProxy(_logic, _data) {
assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(_admin);
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
contract AddressStorage {
mapping(bytes32 => address) private addresses;
function getAddress(bytes32 _key) public view returns (address) {
return addresses[_key];
}
function _setAddress(bytes32 _key, address _value) internal {
addresses[_key] = _value;
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(_admin);
}
}
/**
@title ILendingPoolAddressesProvider interface
@notice provides the interface to fetch the LendingPoolCore address
*/
contract ILendingPoolAddressesProvider {
function getLendingPool() public view returns (address);
function setLendingPoolImpl(address _pool) public;
function getLendingPoolCore() public view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public;
function getLendingPoolConfigurator() public view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public;
function getLendingPoolDataProvider() public view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public;
function getLendingPoolParametersProvider() public view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public;
function getTokenDistributor() public view returns (address);
function setTokenDistributor(address _tokenDistributor) public;
function getFeeProvider() public view returns (address);
function setFeeProviderImpl(address _feeProvider) public;
function getLendingPoolLiquidationManager() public view returns (address);
function setLendingPoolLiquidationManager(address _manager) public;
function getLendingPoolManager() public view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public;
function getPriceOracle() public view returns (address);
function setPriceOracle(address _priceOracle) public;
function getLendingRateOracle() public view returns (address);
function setLendingRateOracle(address _lendingRateOracle) public;
}
/**
* @title LendingPoolAddressesProvider contract
* @notice Is the main registry of the protocol. All the different components of the protocol are accessible
* through the addresses provider.
* @author Aave
**/
contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider, AddressStorage {
//events
event LendingPoolUpdated(address indexed newAddress);
event LendingPoolCoreUpdated(address indexed newAddress);
event LendingPoolParametersProviderUpdated(address indexed newAddress);
event LendingPoolManagerUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolLiquidationManagerUpdated(address indexed newAddress);
event LendingPoolDataProviderUpdated(address indexed newAddress);
event EthereumAddressUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event FeeProviderUpdated(address indexed newAddress);
event TokenDistributorUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
bytes32 private constant LENDING_POOL = "LENDING_POOL";
bytes32 private constant LENDING_POOL_CORE = "LENDING_POOL_CORE";
bytes32 private constant LENDING_POOL_CONFIGURATOR = "LENDING_POOL_CONFIGURATOR";
bytes32 private constant LENDING_POOL_PARAMETERS_PROVIDER = "PARAMETERS_PROVIDER";
bytes32 private constant LENDING_POOL_MANAGER = "LENDING_POOL_MANAGER";
bytes32 private constant LENDING_POOL_LIQUIDATION_MANAGER = "LIQUIDATION_MANAGER";
bytes32 private constant LENDING_POOL_FLASHLOAN_PROVIDER = "FLASHLOAN_PROVIDER";
bytes32 private constant DATA_PROVIDER = "DATA_PROVIDER";
bytes32 private constant ETHEREUM_ADDRESS = "ETHEREUM_ADDRESS";
bytes32 private constant PRICE_ORACLE = "PRICE_ORACLE";
bytes32 private constant LENDING_RATE_ORACLE = "LENDING_RATE_ORACLE";
bytes32 private constant FEE_PROVIDER = "FEE_PROVIDER";
bytes32 private constant WALLET_BALANCE_PROVIDER = "WALLET_BALANCE_PROVIDER";
bytes32 private constant TOKEN_DISTRIBUTOR = "TOKEN_DISTRIBUTOR";
/**
* @dev returns the address of the LendingPool proxy
* @return the lending pool proxy address
**/
function getLendingPool() public view returns (address) {
return getAddress(LENDING_POOL);
}
/**
* @dev updates the implementation of the lending pool
* @param _pool the new lending pool implementation
**/
function setLendingPoolImpl(address _pool) public onlyOwner {
updateImplInternal(LENDING_POOL, _pool);
emit LendingPoolUpdated(_pool);
}
/**
* @dev returns the address of the LendingPoolCore proxy
* @return the lending pool core proxy address
*/
function getLendingPoolCore() public view returns (address payable) {
address payable core = address(uint160(getAddress(LENDING_POOL_CORE)));
return core;
}
/**
* @dev updates the implementation of the lending pool core
* @param _lendingPoolCore the new lending pool core implementation
**/
function setLendingPoolCoreImpl(address _lendingPoolCore) public onlyOwner {
updateImplInternal(LENDING_POOL_CORE, _lendingPoolCore);
emit LendingPoolCoreUpdated(_lendingPoolCore);
}
/**
* @dev returns the address of the LendingPoolConfigurator proxy
* @return the lending pool configurator proxy address
**/
function getLendingPoolConfigurator() public view returns (address) {
return getAddress(LENDING_POOL_CONFIGURATOR);
}
/**
* @dev updates the implementation of the lending pool configurator
* @param _configurator the new lending pool configurator implementation
**/
function setLendingPoolConfiguratorImpl(address _configurator) public onlyOwner {
updateImplInternal(LENDING_POOL_CONFIGURATOR, _configurator);
emit LendingPoolConfiguratorUpdated(_configurator);
}
/**
* @dev returns the address of the LendingPoolDataProvider proxy
* @return the lending pool data provider proxy address
*/
function getLendingPoolDataProvider() public view returns (address) {
return getAddress(DATA_PROVIDER);
}
/**
* @dev updates the implementation of the lending pool data provider
* @param _provider the new lending pool data provider implementation
**/
function setLendingPoolDataProviderImpl(address _provider) public onlyOwner {
updateImplInternal(DATA_PROVIDER, _provider);
emit LendingPoolDataProviderUpdated(_provider);
}
/**
* @dev returns the address of the LendingPoolParametersProvider proxy
* @return the address of the Lending pool parameters provider proxy
**/
function getLendingPoolParametersProvider() public view returns (address) {
return getAddress(LENDING_POOL_PARAMETERS_PROVIDER);
}
/**
* @dev updates the implementation of the lending pool parameters provider
* @param _parametersProvider the new lending pool parameters provider implementation
**/
function setLendingPoolParametersProviderImpl(address _parametersProvider) public onlyOwner {
updateImplInternal(LENDING_POOL_PARAMETERS_PROVIDER, _parametersProvider);
emit LendingPoolParametersProviderUpdated(_parametersProvider);
}
/**
* @dev returns the address of the FeeProvider proxy
* @return the address of the Fee provider proxy
**/
function getFeeProvider() public view returns (address) {
return getAddress(FEE_PROVIDER);
}
/**
* @dev updates the implementation of the FeeProvider proxy
* @param _feeProvider the new lending pool fee provider implementation
**/
function setFeeProviderImpl(address _feeProvider) public onlyOwner {
updateImplInternal(FEE_PROVIDER, _feeProvider);
emit FeeProviderUpdated(_feeProvider);
}
/**
* @dev returns the address of the LendingPoolLiquidationManager. Since the manager is used
* through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence
* the addresses are changed directly.
* @return the address of the Lending pool liquidation manager
**/
function getLendingPoolLiquidationManager() public view returns (address) {
return getAddress(LENDING_POOL_LIQUIDATION_MANAGER);
}
/**
* @dev updates the address of the Lending pool liquidation manager
* @param _manager the new lending pool liquidation manager address
**/
function setLendingPoolLiquidationManager(address _manager) public onlyOwner {
_setAddress(LENDING_POOL_LIQUIDATION_MANAGER, _manager);
emit LendingPoolLiquidationManagerUpdated(_manager);
}
/**
* @dev the functions below are storing specific addresses that are outside the context of the protocol
* hence the upgradable proxy pattern is not used
**/
function getLendingPoolManager() public view returns (address) {
return getAddress(LENDING_POOL_MANAGER);
}
function setLendingPoolManager(address _lendingPoolManager) public onlyOwner {
_setAddress(LENDING_POOL_MANAGER, _lendingPoolManager);
emit LendingPoolManagerUpdated(_lendingPoolManager);
}
function getPriceOracle() public view returns (address) {
return getAddress(PRICE_ORACLE);
}
function setPriceOracle(address _priceOracle) public onlyOwner {
_setAddress(PRICE_ORACLE, _priceOracle);
emit PriceOracleUpdated(_priceOracle);
}
function getLendingRateOracle() public view returns (address) {
return getAddress(LENDING_RATE_ORACLE);
}
function setLendingRateOracle(address _lendingRateOracle) public onlyOwner {
_setAddress(LENDING_RATE_ORACLE, _lendingRateOracle);
emit LendingRateOracleUpdated(_lendingRateOracle);
}
function getTokenDistributor() public view returns (address) {
return getAddress(TOKEN_DISTRIBUTOR);
}
function setTokenDistributor(address _tokenDistributor) public onlyOwner {
_setAddress(TOKEN_DISTRIBUTOR, _tokenDistributor);
emit TokenDistributorUpdated(_tokenDistributor);
}
/**
* @dev internal function to update the implementation of a specific component of the protocol
* @param _id the id of the contract to be updated
* @param _newAddress the address of the new implementation
**/
function updateImplInternal(bytes32 _id, address _newAddress) internal {
address payable proxyAddress = address(uint160(getAddress(_id)));
InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy(proxyAddress);
bytes memory params = abi.encodeWithSignature("initialize(address)", address(this));
if (proxyAddress == address(0)) {
proxy = new InitializableAdminUpgradeabilityProxy();
proxy.initialize(_newAddress, address(this), params);
_setAddress(_id, address(proxy));
emit ProxyCreated(_id, address(proxy));
} else {
proxy.upgradeToAndCall(_newAddress, params);
}
}
}
contract UintStorage {
mapping(bytes32 => uint256) private uints;
function getUint(bytes32 _key) public view returns (uint256) {
return uints[_key];
}
function _setUint(bytes32 _key, uint256 _value) internal {
uints[_key] = _value;
}
}
/**
* @title LendingPoolParametersProvider
* @author Aave
* @notice stores the configuration parameters of the Lending Pool contract
**/
contract LendingPoolParametersProvider is VersionedInitializable {
uint256 private constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25;
uint256 private constant REBALANCE_DOWN_RATE_DELTA = (1e27)/5;
uint256 private constant FLASHLOAN_FEE_TOTAL = 35;
uint256 private constant FLASHLOAN_FEE_PROTOCOL = 3000;
uint256 constant private DATA_PROVIDER_REVISION = 0x1;
function getRevision() internal pure returns(uint256) {
return DATA_PROVIDER_REVISION;
}
/**
* @dev initializes the LendingPoolParametersProvider after it's added to the proxy
* @param _addressesProvider the address of the LendingPoolAddressesProvider
*/
function initialize(address _addressesProvider) public initializer {
}
/**
* @dev returns the maximum stable rate borrow size, in percentage of the available liquidity.
**/
function getMaxStableRateBorrowSizePercent() external pure returns (uint256) {
return MAX_STABLE_RATE_BORROW_SIZE_PERCENT;
}
/**
* @dev returns the delta between the current stable rate and the user stable rate at
* which the borrow position of the user will be rebalanced (scaled down)
**/
function getRebalanceDownRateDelta() external pure returns (uint256) {
return REBALANCE_DOWN_RATE_DELTA;
}
/**
* @dev returns the fee applied to a flashloan and the portion to redirect to the protocol, in basis points.
**/
function getFlashLoanFeesInBips() external pure returns (uint256, uint256) {
return (FLASHLOAN_FEE_TOTAL, FLASHLOAN_FEE_PROTOCOL);
}
}
/**
* @title CoreLibrary library
* @author Aave
* @notice Defines the data structures of the reserves and the user data
**/
library CoreLibrary {
using SafeMath for uint256;
using WadRayMath for uint256;
enum InterestRateMode {NONE, STABLE, VARIABLE}
uint256 internal constant SECONDS_PER_YEAR = 365 days;
struct UserReserveData {
//principal amount borrowed by the user.
uint256 principalBorrowBalance;
//cumulated variable borrow index for the user. Expressed in ray
uint256 lastVariableBorrowCumulativeIndex;
//origination fee cumulated by the user
uint256 originationFee;
// stable borrow rate at which the user has borrowed. Expressed in ray
uint256 stableBorrowRate;
uint40 lastUpdateTimestamp;
//defines if a specific deposit should or not be used as a collateral in borrows
bool useAsCollateral;
}
struct ReserveData {
/**
* @dev refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
**/
//the liquidity index. Expressed in ray
uint256 lastLiquidityCumulativeIndex;
//the current supply rate. Expressed in ray
uint256 currentLiquidityRate;
//the total borrows of the reserve at a stable rate. Expressed in the currency decimals
uint256 totalBorrowsStable;
//the total borrows of the reserve at a variable rate. Expressed in the currency decimals
uint256 totalBorrowsVariable;
//the current variable borrow rate. Expressed in ray
uint256 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint256 currentStableBorrowRate;
//the current average stable borrow rate (weighted average of all the different stable rate loans). Expressed in ray
uint256 currentAverageStableBorrowRate;
//variable borrow index. Expressed in ray
uint256 lastVariableBorrowCumulativeIndex;
//the ltv of the reserve. Expressed in percentage (0-100)
uint256 baseLTVasCollateral;
//the liquidation threshold of the reserve. Expressed in percentage (0-100)
uint256 liquidationThreshold;
//the liquidation bonus of the reserve. Expressed in percentage
uint256 liquidationBonus;
//the decimals of the reserve asset
uint256 decimals;
/**
* @dev address of the aToken representing the asset
**/
address aTokenAddress;
/**
* @dev address of the interest rate strategy contract
**/
address interestRateStrategyAddress;
uint40 lastUpdateTimestamp;
// borrowingEnabled = true means users can borrow from this reserve
bool borrowingEnabled;
// usageAsCollateralEnabled = true means users can use this reserve as collateral
bool usageAsCollateralEnabled;
// isStableBorrowRateEnabled = true means users can borrow at a stable rate
bool isStableBorrowRateEnabled;
// isActive = true means the reserve has been activated and properly configured
bool isActive;
// isFreezed = true means the reserve only allows repays and redeems, but not deposits, new borrowings or rate swap
bool isFreezed;
}
/**
* @dev returns the ongoing normalized income for the reserve.
* a value of 1e27 means there is no income. As time passes, the income is accrued.
* A value of 2*1e27 means that the income of the reserve is double the initial amount.
* @param _reserve the reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(CoreLibrary.ReserveData storage _reserve)
internal
view
returns (uint256)
{
uint256 cumulated = calculateLinearInterest(
_reserve
.currentLiquidityRate,
_reserve
.lastUpdateTimestamp
)
.rayMul(_reserve.lastLiquidityCumulativeIndex);
return cumulated;
}
/**
* @dev Updates the liquidity cumulative index Ci and variable borrow cumulative index Bvc. Refer to the whitepaper for
* a formal specification.
* @param _self the reserve object
**/
function updateCumulativeIndexes(ReserveData storage _self) internal {
uint256 totalBorrows = getTotalBorrows(_self);
if (totalBorrows > 0) {
//only cumulating if there is any income being produced
uint256 cumulatedLiquidityInterest = calculateLinearInterest(
_self.currentLiquidityRate,
_self.lastUpdateTimestamp
);
_self.lastLiquidityCumulativeIndex = cumulatedLiquidityInterest.rayMul(
_self.lastLiquidityCumulativeIndex
);
uint256 cumulatedVariableBorrowInterest = calculateCompoundedInterest(
_self.currentVariableBorrowRate,
_self.lastUpdateTimestamp
);
_self.lastVariableBorrowCumulativeIndex = cumulatedVariableBorrowInterest.rayMul(
_self.lastVariableBorrowCumulativeIndex
);
}
}
/**
* @dev accumulates a predefined amount of asset to the reserve as a fixed, one time income. Used for example to accumulate
* the flashloan fee to the reserve, and spread it through the depositors.
* @param _self the reserve object
* @param _totalLiquidity the total liquidity available in the reserve
* @param _amount the amount to accomulate
**/
function cumulateToLiquidityIndex(
ReserveData storage _self,
uint256 _totalLiquidity,
uint256 _amount
) internal {
uint256 amountToLiquidityRatio = _amount.wadToRay().rayDiv(_totalLiquidity.wadToRay());
uint256 cumulatedLiquidity = amountToLiquidityRatio.add(WadRayMath.ray());
_self.lastLiquidityCumulativeIndex = cumulatedLiquidity.rayMul(
_self.lastLiquidityCumulativeIndex
);
}
/**
* @dev initializes a reserve
* @param _self the reserve object
* @param _aTokenAddress the address of the overlying atoken contract
* @param _decimals the number of decimals of the underlying asset
* @param _interestRateStrategyAddress the address of the interest rate strategy contract
**/
function init(
ReserveData storage _self,
address _aTokenAddress,
uint256 _decimals,
address _interestRateStrategyAddress
) external {
require(_self.aTokenAddress == address(0), "Reserve has already been initialized");
if (_self.lastLiquidityCumulativeIndex == 0) {
//if the reserve has not been initialized yet
_self.lastLiquidityCumulativeIndex = WadRayMath.ray();
}
if (_self.lastVariableBorrowCumulativeIndex == 0) {
_self.lastVariableBorrowCumulativeIndex = WadRayMath.ray();
}
_self.aTokenAddress = _aTokenAddress;
_self.decimals = _decimals;
_self.interestRateStrategyAddress = _interestRateStrategyAddress;
_self.isActive = true;
_self.isFreezed = false;
}
/**
* @dev enables borrowing on a reserve
* @param _self the reserve object
* @param _stableBorrowRateEnabled true if the stable borrow rate must be enabled by default, false otherwise
**/
function enableBorrowing(ReserveData storage _self, bool _stableBorrowRateEnabled) external {
require(_self.borrowingEnabled == false, "Reserve is already enabled");
_self.borrowingEnabled = true;
_self.isStableBorrowRateEnabled = _stableBorrowRateEnabled;
}
/**
* @dev disables borrowing on a reserve
* @param _self the reserve object
**/
function disableBorrowing(ReserveData storage _self) external {
_self.borrowingEnabled = false;
}
/**
* @dev enables a reserve to be used as collateral
* @param _self the reserve object
* @param _baseLTVasCollateral the loan to value of the asset when used as collateral
* @param _liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized
* @param _liquidationBonus the bonus liquidators receive to liquidate this asset
**/
function enableAsCollateral(
ReserveData storage _self,
uint256 _baseLTVasCollateral,
uint256 _liquidationThreshold,
uint256 _liquidationBonus
) external {
require(
_self.usageAsCollateralEnabled == false,
"Reserve is already enabled as collateral"
);
_self.usageAsCollateralEnabled = true;
_self.baseLTVasCollateral = _baseLTVasCollateral;
_self.liquidationThreshold = _liquidationThreshold;
_self.liquidationBonus = _liquidationBonus;
if (_self.lastLiquidityCumulativeIndex == 0)
_self.lastLiquidityCumulativeIndex = WadRayMath.ray();
}
/**
* @dev disables a reserve as collateral
* @param _self the reserve object
**/
function disableAsCollateral(ReserveData storage _self) external {
_self.usageAsCollateralEnabled = false;
}
/**
* @dev calculates the compounded borrow balance of a user
* @param _self the userReserve object
* @param _reserve the reserve object
* @return the user compounded borrow balance
**/
function getCompoundedBorrowBalance(
CoreLibrary.UserReserveData storage _self,
CoreLibrary.ReserveData storage _reserve
) internal view returns (uint256) {
if (_self.principalBorrowBalance == 0) return 0;
uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToRay();
uint256 compoundedBalance = 0;
uint256 cumulatedInterest = 0;
if (_self.stableBorrowRate > 0) {
cumulatedInterest = calculateCompoundedInterest(
_self.stableBorrowRate,
_self.lastUpdateTimestamp
);
} else {
//variable interest
cumulatedInterest = calculateCompoundedInterest(
_reserve
.currentVariableBorrowRate,
_reserve
.lastUpdateTimestamp
)
.rayMul(_reserve.lastVariableBorrowCumulativeIndex)
.rayDiv(_self.lastVariableBorrowCumulativeIndex);
}
compoundedBalance = principalBorrowBalanceRay.rayMul(cumulatedInterest).rayToWad();
if (compoundedBalance == _self.principalBorrowBalance) {
//solium-disable-next-line
if (_self.lastUpdateTimestamp != block.timestamp) {
//no interest cumulation because of the rounding - we add 1 wei
//as symbolic cumulated interest to avoid interest free loans.
return _self.principalBorrowBalance.add(1 wei);
}
}
return compoundedBalance;
}
/**
* @dev increases the total borrows at a stable rate on a specific reserve and updates the
* average stable rate consequently
* @param _reserve the reserve object
* @param _amount the amount to add to the total borrows stable
* @param _rate the rate at which the amount has been borrowed
**/
function increaseTotalBorrowsStableAndUpdateAverageRate(
ReserveData storage _reserve,
uint256 _amount,
uint256 _rate
) internal {
if(_amount == 0) {
return;
}
uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable;
//updating reserve borrows stable
_reserve.totalBorrowsStable = _reserve.totalBorrowsStable.add(_amount);
//update the average stable rate
//weighted average of all the borrows
uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate);
uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul(
_reserve.currentAverageStableBorrowRate
);
_reserve.currentAverageStableBorrowRate = weightedLastBorrow
.add(weightedPreviousTotalBorrows)
.rayDiv(_reserve.totalBorrowsStable.wadToRay());
}
/**
* @dev decreases the total borrows at a stable rate on a specific reserve and updates the
* average stable rate consequently
* @param _reserve the reserve object
* @param _amount the amount to substract to the total borrows stable
* @param _rate the rate at which the amount has been repaid
**/
function decreaseTotalBorrowsStableAndUpdateAverageRate(
ReserveData storage _reserve,
uint256 _amount,
uint256 _rate
) internal {
uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable;
if (previousTotalBorrowStable == 0 || _amount >= previousTotalBorrowStable) {
_reserve.totalBorrowsStable = 0;
_reserve.currentAverageStableBorrowRate = 0; // no income if there are no stable rate borrows
return;
}
//updating reserve borrows stable
_reserve.totalBorrowsStable = _reserve.totalBorrowsStable.sub(_amount);
//update the average stable rate
//weighted average of all the borrows
uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate);
uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul(
_reserve.currentAverageStableBorrowRate
);
if(
weightedPreviousTotalBorrows <= weightedLastBorrow
) {
_reserve.totalBorrowsStable = 0;
_reserve.currentAverageStableBorrowRate = 0; // no income if there are no stable rate borrows
return;
}
_reserve.currentAverageStableBorrowRate = weightedPreviousTotalBorrows
.sub(weightedLastBorrow)
.rayDiv(_reserve.totalBorrowsStable.wadToRay());
}
/**
* @dev increases the total borrows at a variable rate
* @param _reserve the reserve object
* @param _amount the amount to add to the total borrows variable
**/
function increaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal {
_reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.add(_amount);
}
/**
* @dev decreases the total borrows at a variable rate
* @param _reserve the reserve object
* @param _amount the amount to substract to the total borrows variable
**/
function decreaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal {
require(
_reserve.totalBorrowsVariable >= _amount,
"The amount that is being subtracted from the variable total borrows is incorrect"
);
_reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.sub(_amount);
}
/**
* @dev function to calculate the interest using a linear interest rate formula
* @param _rate the interest rate, in ray
* @param _lastUpdateTimestamp the timestamp of the last update of the interest
* @return the interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 _rate, uint40 _lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp));
uint256 timeDelta = timeDifference.wadToRay().rayDiv(SECONDS_PER_YEAR.wadToRay());
return _rate.rayMul(timeDelta).add(WadRayMath.ray());
}
/**
* @dev function to calculate the interest using a compounded interest rate formula
* @param _rate the interest rate, in ray
* @param _lastUpdateTimestamp the timestamp of the last update of the interest
* @return the interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(uint256 _rate, uint40 _lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp));
uint256 ratePerSecond = _rate.div(SECONDS_PER_YEAR);
return ratePerSecond.add(WadRayMath.ray()).rayPow(timeDifference);
}
/**
* @dev returns the total borrows on the reserve
* @param _reserve the reserve object
* @return the total borrows (stable + variable)
**/
function getTotalBorrows(CoreLibrary.ReserveData storage _reserve)
internal
view
returns (uint256)
{
return _reserve.totalBorrowsStable.add(_reserve.totalBorrowsVariable);
}
}
/**
* @title IPriceOracleGetter interface
* @notice Interface for the Aave price oracle.
**/
interface IPriceOracleGetter {
/**
* @dev returns the asset price in ETH
* @param _asset the address of the asset
* @return the ETH price of the asset
**/
function getAssetPrice(address _asset) external view returns (uint256);
}
/**
* @title IFeeProvider interface
* @notice Interface for the Aave fee provider.
**/
interface IFeeProvider {
function calculateLoanOriginationFee(address _user, uint256 _amount) external view returns (uint256);
function getLoanOriginationFeePercentage() external view returns (uint256);
}
/**
* @title LendingPoolDataProvider contract
* @author Aave
* @notice Implements functions to fetch data from the core, and aggregate them in order to allow computation
* on the compounded balances and the account balances in ETH
**/
contract LendingPoolDataProvider is VersionedInitializable {
using SafeMath for uint256;
using WadRayMath for uint256;
LendingPoolCore public core;
LendingPoolAddressesProvider public addressesProvider;
/**
* @dev specifies the health factor threshold at which the user position is liquidated.
* 1e18 by default, if the health factor drops below 1e18, the loan can be liquidated.
**/
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;
uint256 public constant DATA_PROVIDER_REVISION = 0x1;
function getRevision() internal pure returns (uint256) {
return DATA_PROVIDER_REVISION;
}
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
core = LendingPoolCore(_addressesProvider.getLendingPoolCore());
}
/**
* @dev struct to hold calculateUserGlobalData() local computations
**/
struct UserGlobalDataLocalVars {
uint256 reserveUnitPrice;
uint256 tokenUnit;
uint256 compoundedLiquidityBalance;
uint256 compoundedBorrowBalance;
uint256 reserveDecimals;
uint256 baseLtv;
uint256 liquidationThreshold;
uint256 originationFee;
bool usageAsCollateralEnabled;
bool userUsesReserveAsCollateral;
address currentReserve;
}
/**
* @dev calculates the user data across the reserves.
* this includes the total liquidity/collateral/borrow balances in ETH,
* the average Loan To Value, the average Liquidation Ratio, and the Health factor.
* @param _user the address of the user
* @return the total liquidity, total collateral, total borrow balances of the user in ETH.
* also the average Ltv, liquidation threshold, and the health factor
**/
function calculateUserGlobalData(address _user)
public
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
)
{
IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
UserGlobalDataLocalVars memory vars;
address[] memory reserves = core.getReserves();
for (uint256 i = 0; i < reserves.length; i++) {
vars.currentReserve = reserves[i];
(
vars.compoundedLiquidityBalance,
vars.compoundedBorrowBalance,
vars.originationFee,
vars.userUsesReserveAsCollateral
) = core.getUserBasicReserveData(vars.currentReserve, _user);
if (vars.compoundedLiquidityBalance == 0 && vars.compoundedBorrowBalance == 0) {
continue;
}
//fetch reserve data
(
vars.reserveDecimals,
vars.baseLtv,
vars.liquidationThreshold,
vars.usageAsCollateralEnabled
) = core.getReserveConfiguration(vars.currentReserve);
vars.tokenUnit = 10 ** vars.reserveDecimals;
vars.reserveUnitPrice = oracle.getAssetPrice(vars.currentReserve);
//liquidity and collateral balance
if (vars.compoundedLiquidityBalance > 0) {
uint256 liquidityBalanceETH = vars
.reserveUnitPrice
.mul(vars.compoundedLiquidityBalance)
.div(vars.tokenUnit);
totalLiquidityBalanceETH = totalLiquidityBalanceETH.add(liquidityBalanceETH);
if (vars.usageAsCollateralEnabled && vars.userUsesReserveAsCollateral) {
totalCollateralBalanceETH = totalCollateralBalanceETH.add(liquidityBalanceETH);
currentLtv = currentLtv.add(liquidityBalanceETH.mul(vars.baseLtv));
currentLiquidationThreshold = currentLiquidationThreshold.add(
liquidityBalanceETH.mul(vars.liquidationThreshold)
);
}
}
if (vars.compoundedBorrowBalance > 0) {
totalBorrowBalanceETH = totalBorrowBalanceETH.add(
vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit)
);
totalFeesETH = totalFeesETH.add(
vars.originationFee.mul(vars.reserveUnitPrice).div(vars.tokenUnit)
);
}
}
currentLtv = totalCollateralBalanceETH > 0 ? currentLtv.div(totalCollateralBalanceETH) : 0;
currentLiquidationThreshold = totalCollateralBalanceETH > 0
? currentLiquidationThreshold.div(totalCollateralBalanceETH)
: 0;
healthFactor = calculateHealthFactorFromBalancesInternal(
totalCollateralBalanceETH,
totalBorrowBalanceETH,
totalFeesETH,
currentLiquidationThreshold
);
healthFactorBelowThreshold = healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
struct balanceDecreaseAllowedLocalVars {
uint256 decimals;
uint256 collateralBalanceETH;
uint256 borrowBalanceETH;
uint256 totalFeesETH;
uint256 currentLiquidationThreshold;
uint256 reserveLiquidationThreshold;
uint256 amountToDecreaseETH;
uint256 collateralBalancefterDecrease;
uint256 liquidationThresholdAfterDecrease;
uint256 healthFactorAfterDecrease;
bool reserveUsageAsCollateralEnabled;
}
/**
* @dev check if a specific balance decrease is allowed (i.e. doesn't bring the user borrow position health factor under 1e18)
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to decrease
* @return true if the decrease of the balance is allowed
**/
function balanceDecreaseAllowed(address _reserve, address _user, uint256 _amount)
external
view
returns (bool)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
balanceDecreaseAllowedLocalVars memory vars;
(
vars.decimals,
,
vars.reserveLiquidationThreshold,
vars.reserveUsageAsCollateralEnabled
) = core.getReserveConfiguration(_reserve);
if (
!vars.reserveUsageAsCollateralEnabled ||
!core.isUserUseReserveAsCollateralEnabled(_reserve, _user)
) {
return true; //if reserve is not used as collateral, no reasons to block the transfer
}
(
,
vars.collateralBalanceETH,
vars.borrowBalanceETH,
vars.totalFeesETH,
,
vars.currentLiquidationThreshold,
,
) = calculateUserGlobalData(_user);
if (vars.borrowBalanceETH == 0) {
return true; //no borrows - no reasons to block the transfer
}
IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
vars.amountToDecreaseETH = oracle.getAssetPrice(_reserve).mul(_amount).div(
10 ** vars.decimals
);
vars.collateralBalancefterDecrease = vars.collateralBalanceETH.sub(
vars.amountToDecreaseETH
);
//if there is a borrow, there can't be 0 collateral
if (vars.collateralBalancefterDecrease == 0) {
return false;
}
vars.liquidationThresholdAfterDecrease = vars
.collateralBalanceETH
.mul(vars.currentLiquidationThreshold)
.sub(vars.amountToDecreaseETH.mul(vars.reserveLiquidationThreshold))
.div(vars.collateralBalancefterDecrease);
uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalancesInternal(
vars.collateralBalancefterDecrease,
vars.borrowBalanceETH,
vars.totalFeesETH,
vars.liquidationThresholdAfterDecrease
);
return healthFactorAfterDecrease > HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
/**
* @notice calculates the amount of collateral needed in ETH to cover a new borrow.
* @param _reserve the reserve from which the user wants to borrow
* @param _amount the amount the user wants to borrow
* @param _fee the fee for the amount that the user needs to cover
* @param _userCurrentBorrowBalanceTH the current borrow balance of the user (before the borrow)
* @param _userCurrentLtv the average ltv of the user given his current collateral
* @return the total amount of collateral in ETH to cover the current borrow balance + the new amount + fee
**/
function calculateCollateralNeededInETH(
address _reserve,
uint256 _amount,
uint256 _fee,
uint256 _userCurrentBorrowBalanceTH,
uint256 _userCurrentFeesETH,
uint256 _userCurrentLtv
) external view returns (uint256) {
uint256 reserveDecimals = core.getReserveDecimals(_reserve);
IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
uint256 requestedBorrowAmountETH = oracle
.getAssetPrice(_reserve)
.mul(_amount.add(_fee))
.div(10 ** reserveDecimals); //price is in ether
//add the current already borrowed amount to the amount requested to calculate the total collateral needed.
uint256 collateralNeededInETH = _userCurrentBorrowBalanceTH
.add(_userCurrentFeesETH)
.add(requestedBorrowAmountETH)
.mul(100)
.div(_userCurrentLtv); //LTV is calculated in percentage
return collateralNeededInETH;
}
/**
* @dev calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the
* average Loan To Value.
* @param collateralBalanceETH the total collateral balance
* @param borrowBalanceETH the total borrow balance
* @param totalFeesETH the total fees
* @param ltv the average loan to value
* @return the amount available to borrow in ETH for the user
**/
function calculateAvailableBorrowsETHInternal(
uint256 collateralBalanceETH,
uint256 borrowBalanceETH,
uint256 totalFeesETH,
uint256 ltv
) internal view returns (uint256) {
uint256 availableBorrowsETH = collateralBalanceETH.mul(ltv).div(100); //ltv is in percentage
if (availableBorrowsETH < borrowBalanceETH) {
return 0;
}
availableBorrowsETH = availableBorrowsETH.sub(borrowBalanceETH.add(totalFeesETH));
//calculate fee
uint256 borrowFee = IFeeProvider(addressesProvider.getFeeProvider())
.calculateLoanOriginationFee(msg.sender, availableBorrowsETH);
return availableBorrowsETH.sub(borrowFee);
}
/**
* @dev calculates the health factor from the corresponding balances
* @param collateralBalanceETH the total collateral balance in ETH
* @param borrowBalanceETH the total borrow balance in ETH
* @param totalFeesETH the total fees in ETH
* @param liquidationThreshold the avg liquidation threshold
**/
function calculateHealthFactorFromBalancesInternal(
uint256 collateralBalanceETH,
uint256 borrowBalanceETH,
uint256 totalFeesETH,
uint256 liquidationThreshold
) internal pure returns (uint256) {
if (borrowBalanceETH == 0) return uint256(-1);
return
(collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv(
borrowBalanceETH.add(totalFeesETH)
);
}
/**
* @dev returns the health factor liquidation threshold
**/
function getHealthFactorLiquidationThreshold() public pure returns (uint256) {
return HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
/**
* @dev accessory functions to fetch data from the lendingPoolCore
**/
function getReserveConfigurationData(address _reserve)
external
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
)
{
(, ltv, liquidationThreshold, usageAsCollateralEnabled) = core.getReserveConfiguration(
_reserve
);
stableBorrowRateEnabled = core.getReserveIsStableBorrowRateEnabled(_reserve);
borrowingEnabled = core.isReserveBorrowingEnabled(_reserve);
isActive = core.getReserveIsActive(_reserve);
liquidationBonus = core.getReserveLiquidationBonus(_reserve);
rateStrategyAddress = core.getReserveInterestRateStrategyAddress(_reserve);
}
function getReserveData(address _reserve)
external
view
returns (
uint256 totalLiquidity,
uint256 availableLiquidity,
uint256 totalBorrowsStable,
uint256 totalBorrowsVariable,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 utilizationRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
address aTokenAddress,
uint40 lastUpdateTimestamp
)
{
totalLiquidity = core.getReserveTotalLiquidity(_reserve);
availableLiquidity = core.getReserveAvailableLiquidity(_reserve);
totalBorrowsStable = core.getReserveTotalBorrowsStable(_reserve);
totalBorrowsVariable = core.getReserveTotalBorrowsVariable(_reserve);
liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);
variableBorrowRate = core.getReserveCurrentVariableBorrowRate(_reserve);
stableBorrowRate = core.getReserveCurrentStableBorrowRate(_reserve);
averageStableBorrowRate = core.getReserveCurrentAverageStableBorrowRate(_reserve);
utilizationRate = core.getReserveUtilizationRate(_reserve);
liquidityIndex = core.getReserveLiquidityCumulativeIndex(_reserve);
variableBorrowIndex = core.getReserveVariableBorrowsCumulativeIndex(_reserve);
aTokenAddress = core.getReserveATokenAddress(_reserve);
lastUpdateTimestamp = core.getReserveLastUpdate(_reserve);
}
function getUserAccountData(address _user)
external
view
returns (
uint256 totalLiquidityETH,
uint256 totalCollateralETH,
uint256 totalBorrowsETH,
uint256 totalFeesETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
(
totalLiquidityETH,
totalCollateralETH,
totalBorrowsETH,
totalFeesETH,
ltv,
currentLiquidationThreshold,
healthFactor,
) = calculateUserGlobalData(_user);
availableBorrowsETH = calculateAvailableBorrowsETHInternal(
totalCollateralETH,
totalBorrowsETH,
totalFeesETH,
ltv
);
}
function getUserReserveData(address _reserve, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentBorrowBalance,
uint256 principalBorrowBalance,
uint256 borrowRateMode,
uint256 borrowRate,
uint256 liquidityRate,
uint256 originationFee,
uint256 variableBorrowIndex,
uint256 lastUpdateTimestamp,
bool usageAsCollateralEnabled
)
{
currentATokenBalance = AToken(core.getReserveATokenAddress(_reserve)).balanceOf(_user);
CoreLibrary.InterestRateMode mode = core.getUserCurrentBorrowRateMode(_reserve, _user);
(principalBorrowBalance, currentBorrowBalance, ) = core.getUserBorrowBalances(
_reserve,
_user
);
//default is 0, if mode == CoreLibrary.InterestRateMode.NONE
if (mode == CoreLibrary.InterestRateMode.STABLE) {
borrowRate = core.getUserCurrentStableBorrowRate(_reserve, _user);
} else if (mode == CoreLibrary.InterestRateMode.VARIABLE) {
borrowRate = core.getReserveCurrentVariableBorrowRate(_reserve);
}
borrowRateMode = uint256(mode);
liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);
originationFee = core.getUserOriginationFee(_reserve, _user);
variableBorrowIndex = core.getUserVariableBorrowCumulativeIndex(_reserve, _user);
lastUpdateTimestamp = core.getUserLastUpdate(_reserve, _user);
usageAsCollateralEnabled = core.isUserUseReserveAsCollateralEnabled(_reserve, _user);
}
}
/**
* @title Aave ERC20 AToken
*
* @dev Implementation of the interest bearing token for the DLP protocol.
* @author Aave
*/
contract AToken is ERC20, ERC20Detailed {
using WadRayMath for uint256;
uint256 public constant UINT_MAX_VALUE = uint256(-1);
/**
* @dev emitted after the redeem action
* @param _from the address performing the redeem
* @param _value the amount to be redeemed
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event Redeem(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted after the mint action
* @param _from the address performing the mint
* @param _value the amount to be minted
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event MintOnDeposit(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted during the liquidation action, when the liquidator reclaims the underlying
* asset
* @param _from the address from which the tokens are being burned
* @param _value the amount to be burned
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event BurnOnLiquidation(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted during the transfer action
* @param _from the address from which the tokens are being transferred
* @param _to the adress of the destination
* @param _value the amount to be minted
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _toBalanceIncrease the cumulated balance since the last update of the destination
* @param _fromIndex the last index of the user
* @param _toIndex the last index of the liquidator
**/
event BalanceTransfer(
address indexed _from,
address indexed _to,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _toBalanceIncrease,
uint256 _fromIndex,
uint256 _toIndex
);
/**
* @dev emitted when the accumulation of the interest
* by an user is redirected to another user
* @param _from the address from which the interest is being redirected
* @param _to the adress of the destination
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event InterestStreamRedirected(
address indexed _from,
address indexed _to,
uint256 _redirectedBalance,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted when the redirected balance of an user is being updated
* @param _targetAddress the address of which the balance is being updated
* @param _targetBalanceIncrease the cumulated balance since the last update of the target
* @param _targetIndex the last index of the user
* @param _redirectedBalanceAdded the redirected balance being added
* @param _redirectedBalanceRemoved the redirected balance being removed
**/
event RedirectedBalanceUpdated(
address indexed _targetAddress,
uint256 _targetBalanceIncrease,
uint256 _targetIndex,
uint256 _redirectedBalanceAdded,
uint256 _redirectedBalanceRemoved
);
event InterestRedirectionAllowanceChanged(
address indexed _from,
address indexed _to
);
address public underlyingAssetAddress;
mapping (address => uint256) private userIndexes;
mapping (address => address) private interestRedirectionAddresses;
mapping (address => uint256) private redirectedBalances;
mapping (address => address) private interestRedirectionAllowances;
LendingPoolAddressesProvider private addressesProvider;
LendingPoolCore private core;
LendingPool private pool;
LendingPoolDataProvider private dataProvider;
modifier onlyLendingPool {
require(
msg.sender == address(pool),
"The caller of this function must be a lending pool"
);
_;
}
modifier whenTransferAllowed(address _from, uint256 _amount) {
require(isTransferAllowed(_from, _amount), "Transfer cannot be allowed.");
_;
}
constructor(
LendingPoolAddressesProvider _addressesProvider,
address _underlyingAsset,
uint8 _underlyingAssetDecimals,
string memory _name,
string memory _symbol
) public ERC20Detailed(_name, _symbol, _underlyingAssetDecimals) {
addressesProvider = _addressesProvider;
core = LendingPoolCore(addressesProvider.getLendingPoolCore());
pool = LendingPool(addressesProvider.getLendingPool());
dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());
underlyingAssetAddress = _underlyingAsset;
}
/**
* @notice ERC20 implementation internal function backing transfer() and transferFrom()
* @dev validates the transfer before allowing it. NOTE: This is not standard ERC20 behavior
**/
function _transfer(address _from, address _to, uint256 _amount) internal whenTransferAllowed(_from, _amount) {
executeTransferInternal(_from, _to, _amount);
}
/**
* @dev redirects the interest generated to a target address.
* when the interest is redirected, the user balance is added to
* the recepient redirected balance.
* @param _to the address to which the interest will be redirected
**/
function redirectInterestStream(address _to) external {
redirectInterestStreamInternal(msg.sender, _to);
}
/**
* @dev redirects the interest generated by _from to a target address.
* when the interest is redirected, the user balance is added to
* the recepient redirected balance. The caller needs to have allowance on
* the interest redirection to be able to execute the function.
* @param _from the address of the user whom interest is being redirected
* @param _to the address to which the interest will be redirected
**/
function redirectInterestStreamOf(address _from, address _to) external {
require(
msg.sender == interestRedirectionAllowances[_from],
"Caller is not allowed to redirect the interest of the user"
);
redirectInterestStreamInternal(_from,_to);
}
/**
* @dev gives allowance to an address to execute the interest redirection
* on behalf of the caller.
* @param _to the address to which the interest will be redirected. Pass address(0) to reset
* the allowance.
**/
function allowInterestRedirectionTo(address _to) external {
require(_to != msg.sender, "User cannot give allowance to himself");
interestRedirectionAllowances[msg.sender] = _to;
emit InterestRedirectionAllowanceChanged(
msg.sender,
_to
);
}
/**
* @dev redeems aToken for the underlying asset
* @param _amount the amount being redeemed
**/
function redeem(uint256 _amount) external {
require(_amount > 0, "Amount to redeem needs to be > 0");
//cumulates the balance of the user
(,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 index) = cumulateBalanceInternal(msg.sender);
uint256 amountToRedeem = _amount;
//if amount is equal to uint(-1), the user wants to redeem everything
if(_amount == UINT_MAX_VALUE){
amountToRedeem = currentBalance;
}
require(amountToRedeem <= currentBalance, "User cannot redeem more than the available balance");
//check that the user is allowed to redeem the amount
require(isTransferAllowed(msg.sender, amountToRedeem), "Transfer cannot be allowed.");
//if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest,
//and removing the amount to redeem
updateRedirectedBalanceOfRedirectionAddressInternal(msg.sender, balanceIncrease, amountToRedeem);
// burns tokens equivalent to the amount requested
_burn(msg.sender, amountToRedeem);
bool userIndexReset = false;
//reset the user data if the remaining balance is 0
if(currentBalance.sub(amountToRedeem) == 0){
userIndexReset = resetDataOnZeroBalanceInternal(msg.sender);
}
// executes redeem of the underlying asset
pool.redeemUnderlying(
underlyingAssetAddress,
msg.sender,
amountToRedeem,
currentBalance.sub(amountToRedeem)
);
emit Redeem(msg.sender, amountToRedeem, balanceIncrease, userIndexReset ? 0 : index);
}
/**
* @dev mints token in the event of users depositing the underlying asset into the lending pool
* only lending pools can call this function
* @param _account the address receiving the minted tokens
* @param _amount the amount of tokens to mint
*/
function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool {
//cumulates the balance of the user
(,
,
uint256 balanceIncrease,
uint256 index) = cumulateBalanceInternal(_account);
//if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest
//and the amount deposited
updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0);
//mint an equivalent amount of tokens to cover the new deposit
_mint(_account, _amount);
emit MintOnDeposit(_account, _amount, balanceIncrease, index);
}
/**
* @dev burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset
* Transfer of the liquidated asset is executed by the lending pool contract.
* only lending pools can call this function
* @param _account the address from which burn the aTokens
* @param _value the amount to burn
**/
function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool {
//cumulates the balance of the user being liquidated
(,uint256 accountBalance,uint256 balanceIncrease,uint256 index) = cumulateBalanceInternal(_account);
//adds the accrued interest and substracts the burned amount to
//the redirected balance
updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease, _value);
//burns the requested amount of tokens
_burn(_account, _value);
bool userIndexReset = false;
//reset the user data if the remaining balance is 0
if(accountBalance.sub(_value) == 0){
userIndexReset = resetDataOnZeroBalanceInternal(_account);
}
emit BurnOnLiquidation(_account, _value, balanceIncrease, userIndexReset ? 0 : index);
}
/**
* @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* only lending pools can call this function
* @param _from the address from which transfer the aTokens
* @param _to the destination address
* @param _value the amount to transfer
**/
function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool {
//being a normal transfer, the Transfer() and BalanceTransfer() are emitted
//so no need to emit a specific event here
executeTransferInternal(_from, _to, _value);
}
/**
* @dev calculates the balance of the user, which is the
* principal balance + interest generated by the principal balance + interest generated by the redirected balance
* @param _user the user for which the balance is being calculated
* @return the total balance of the user
**/
function balanceOf(address _user) public view returns(uint256) {
//current principal balance of the user
uint256 currentPrincipalBalance = super.balanceOf(_user);
//balance redirected by other users to _user for interest rate accrual
uint256 redirectedBalance = redirectedBalances[_user];
if(currentPrincipalBalance == 0 && redirectedBalance == 0){
return 0;
}
//if the _user is not redirecting the interest to anybody, accrues
//the interest for himself
if(interestRedirectionAddresses[_user] == address(0)){
//accruing for himself means that both the principal balance and
//the redirected balance partecipate in the interest
return calculateCumulatedBalanceInternal(
_user,
currentPrincipalBalance.add(redirectedBalance)
)
.sub(redirectedBalance);
}
else {
//if the user redirected the interest, then only the redirected
//balance generates interest. In that case, the interest generated
//by the redirected balance is added to the current principal balance.
return currentPrincipalBalance.add(
calculateCumulatedBalanceInternal(
_user,
redirectedBalance
)
.sub(redirectedBalance)
);
}
}
/**
* @dev returns the principal balance of the user. The principal balance is the last
* updated stored balance, which does not consider the perpetually accruing interest.
* @param _user the address of the user
* @return the principal balance of the user
**/
function principalBalanceOf(address _user) external view returns(uint256) {
return super.balanceOf(_user);
}
/**
* @dev calculates the total supply of the specific aToken
* since the balance of every single user increases over time, the total supply
* does that too.
* @return the current total supply
**/
function totalSupply() public view returns(uint256) {
uint256 currentSupplyPrincipal = super.totalSupply();
if(currentSupplyPrincipal == 0){
return 0;
}
return currentSupplyPrincipal
.wadToRay()
.rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))
.rayToWad();
}
/**
* @dev Used to validate transfers before actually executing them.
* @param _user address of the user to check
* @param _amount the amount to check
* @return true if the _user can transfer _amount, false otherwise
**/
function isTransferAllowed(address _user, uint256 _amount) public view returns (bool) {
return dataProvider.balanceDecreaseAllowed(underlyingAssetAddress, _user, _amount);
}
/**
* @dev returns the last index of the user, used to calculate the balance of the user
* @param _user address of the user
* @return the last user index
**/
function getUserIndex(address _user) external view returns(uint256) {
return userIndexes[_user];
}
/**
* @dev returns the address to which the interest is redirected
* @param _user address of the user
* @return 0 if there is no redirection, an address otherwise
**/
function getInterestRedirectionAddress(address _user) external view returns(address) {
return interestRedirectionAddresses[_user];
}
/**
* @dev returns the redirected balance of the user. The redirected balance is the balance
* redirected by other accounts to the user, that is accrueing interest for him.
* @param _user address of the user
* @return the total redirected balance
**/
function getRedirectedBalance(address _user) external view returns(uint256) {
return redirectedBalances[_user];
}
/**
* @dev accumulates the accrued interest of the user to the principal balance
* @param _user the address of the user for which the interest is being accumulated
* @return the previous principal balance, the new principal balance, the balance increase
* and the new user index
**/
function cumulateBalanceInternal(address _user)
internal
returns(uint256, uint256, uint256, uint256) {
uint256 previousPrincipalBalance = super.balanceOf(_user);
//calculate the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance);
//mints an amount of tokens equivalent to the amount accumulated
_mint(_user, balanceIncrease);
//updates the user index
uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease,
index
);
}
/**
* @dev updates the redirected balance of the user. If the user is not redirecting his
* interest, nothing is executed.
* @param _user the address of the user for which the interest is being accumulated
* @param _balanceToAdd the amount to add to the redirected balance
* @param _balanceToRemove the amount to remove from the redirected balance
**/
function updateRedirectedBalanceOfRedirectionAddressInternal(
address _user,
uint256 _balanceToAdd,
uint256 _balanceToRemove
) internal {
address redirectionAddress = interestRedirectionAddresses[_user];
//if there isn't any redirection, nothing to be done
if(redirectionAddress == address(0)){
return;
}
//compound balances of the redirected address
(,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress);
//updating the redirected balance
redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress]
.add(_balanceToAdd)
.sub(_balanceToRemove);
//if the interest of redirectionAddress is also being redirected, we need to update
//the redirected balance of the redirection target by adding the balance increase
address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress];
if(targetOfRedirectionAddress != address(0)){
redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease);
}
emit RedirectedBalanceUpdated(
redirectionAddress,
balanceIncrease,
index,
_balanceToAdd,
_balanceToRemove
);
}
/**
* @dev calculate the interest accrued by _user on a specific balance
* @param _user the address of the user for which the interest is being accumulated
* @param _balance the balance on which the interest is calculated
* @return the interest rate accrued
**/
function calculateCumulatedBalanceInternal(
address _user,
uint256 _balance
) internal view returns (uint256) {
return _balance
.wadToRay()
.rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))
.rayDiv(userIndexes[_user])
.rayToWad();
}
/**
* @dev executes the transfer of aTokens, invoked by both _transfer() and
* transferOnLiquidation()
* @param _from the address from which transfer the aTokens
* @param _to the destination address
* @param _value the amount to transfer
**/
function executeTransferInternal(
address _from,
address _to,
uint256 _value
) internal {
require(_value > 0, "Transferred amount needs to be greater than zero");
//cumulate the balance of the sender
(,
uint256 fromBalance,
uint256 fromBalanceIncrease,
uint256 fromIndex
) = cumulateBalanceInternal(_from);
//cumulate the balance of the receiver
(,
,
uint256 toBalanceIncrease,
uint256 toIndex
) = cumulateBalanceInternal(_to);
//if the sender is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and removes the amount
//being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(_from, fromBalanceIncrease, _value);
//if the receiver is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and the amount
//being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(_to, toBalanceIncrease.add(_value), 0);
//performs the transfer
super._transfer(_from, _to, _value);
bool fromIndexReset = false;
//reset the user data if the remaining balance is 0
if(fromBalance.sub(_value) == 0){
fromIndexReset = resetDataOnZeroBalanceInternal(_from);
}
emit BalanceTransfer(
_from,
_to,
_value,
fromBalanceIncrease,
toBalanceIncrease,
fromIndexReset ? 0 : fromIndex,
toIndex
);
}
/**
* @dev executes the redirection of the interest from one address to another.
* immediately after redirection, the destination address will start to accrue interest.
* @param _from the address from which transfer the aTokens
* @param _to the destination address
**/
function redirectInterestStreamInternal(
address _from,
address _to
) internal {
address currentRedirectionAddress = interestRedirectionAddresses[_from];
require(_to != currentRedirectionAddress, "Interest is already redirected to the user");
//accumulates the accrued interest to the principal
(uint256 previousPrincipalBalance,
uint256 fromBalance,
uint256 balanceIncrease,
uint256 fromIndex) = cumulateBalanceInternal(_from);
require(fromBalance > 0, "Interest stream can only be redirected if there is a valid balance");
//if the user is already redirecting the interest to someone, before changing
//the redirection address we substract the redirected balance of the previous
//recipient
if(currentRedirectionAddress != address(0)){
updateRedirectedBalanceOfRedirectionAddressInternal(_from,0, previousPrincipalBalance);
}
//if the user is redirecting the interest back to himself,
//we simply set to 0 the interest redirection address
if(_to == _from) {
interestRedirectionAddresses[_from] = address(0);
emit InterestStreamRedirected(
_from,
address(0),
fromBalance,
balanceIncrease,
fromIndex
);
return;
}
//first set the redirection address to the new recipient
interestRedirectionAddresses[_from] = _to;
//adds the user balance to the redirected balance of the destination
updateRedirectedBalanceOfRedirectionAddressInternal(_from,fromBalance,0);
emit InterestStreamRedirected(
_from,
_to,
fromBalance,
balanceIncrease,
fromIndex
);
}
/**
* @dev function to reset the interest stream redirection and the user index, if the
* user has no balance left.
* @param _user the address of the user
* @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value
**/
function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) {
//if the user has 0 principal balance, the interest stream redirection gets reset
interestRedirectionAddresses[_user] = address(0);
//emits a InterestStreamRedirected event to notify that the redirection has been reset
emit InterestStreamRedirected(_user, address(0),0,0,0);
//if the redirected balance is also 0, we clear up the user index
if(redirectedBalances[_user] == 0){
userIndexes[_user] = 0;
return true;
}
else{
return false;
}
}
}
/**
* @title IFlashLoanReceiver interface
* @notice Interface for the Aave fee IFlashLoanReceiver.
* @author Aave
* @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract
**/
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
/**
* @title ILendingRateOracle interface
* @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations
**/
interface ILendingRateOracle {
/**
@dev returns the market borrow rate in ray
**/
function getMarketBorrowRate(address _asset) external view returns (uint256);
/**
@dev sets the market borrow rate. Rate value must be in ray
**/
function setMarketBorrowRate(address _asset, uint256 _rate) external;
}
/**
@title IReserveInterestRateStrategyInterface interface
@notice Interface for the calculation of the interest rates.
*/
interface IReserveInterestRateStrategy {
/**
* @dev returns the base variable borrow rate, in rays
*/
function getBaseVariableBorrowRate() external view returns (uint256);
/**
* @dev calculates the liquidity, stable, and variable rates depending on the current utilization rate
* and the base parameters
*
*/
function calculateInterestRates(
address _reserve,
uint256 _utilizationRate,
uint256 _totalBorrowsStable,
uint256 _totalBorrowsVariable,
uint256 _averageStableBorrowRate)
external
view
returns (uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate);
}
library EthAddressLib {
/**
* @dev returns the address used within the protocol to identify ETH
* @return the address assigned to ETH
*/
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
/**
* @title LendingPool contract
* @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data
* @author Aave
**/
contract LendingPool is ReentrancyGuard, VersionedInitializable {
using SafeMath for uint256;
using WadRayMath for uint256;
using Address for address;
LendingPoolAddressesProvider public addressesProvider;
LendingPoolCore public core;
LendingPoolDataProvider public dataProvider;
LendingPoolParametersProvider public parametersProvider;
IFeeProvider feeProvider;
/**
* @dev emitted on deposit
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _referral the referral number of the action
* @param _timestamp the timestamp of the action
**/
event Deposit(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint16 indexed _referral,
uint256 _timestamp
);
/**
* @dev emitted during a redeem action.
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _timestamp the timestamp of the action
**/
event RedeemUnderlying(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _timestamp
);
/**
* @dev emitted on borrow
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _borrowRateMode the rate mode, can be either 1-stable or 2-variable
* @param _borrowRate the rate at which the user has borrowed
* @param _originationFee the origination fee to be paid by the user
* @param _borrowBalanceIncrease the balance increase since the last borrow, 0 if it's the first time borrowing
* @param _referral the referral number of the action
* @param _timestamp the timestamp of the action
**/
event Borrow(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _borrowRateMode,
uint256 _borrowRate,
uint256 _originationFee,
uint256 _borrowBalanceIncrease,
uint16 indexed _referral,
uint256 _timestamp
);
/**
* @dev emitted on repay
* @param _reserve the address of the reserve
* @param _user the address of the user for which the repay has been executed
* @param _repayer the address of the user that has performed the repay action
* @param _amountMinusFees the amount repaid minus fees
* @param _fees the fees repaid
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event Repay(
address indexed _reserve,
address indexed _user,
address indexed _repayer,
uint256 _amountMinusFees,
uint256 _fees,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a user performs a rate swap
* @param _reserve the address of the reserve
* @param _user the address of the user executing the swap
* @param _newRateMode the new interest rate mode
* @param _newRate the new borrow rate
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event Swap(
address indexed _reserve,
address indexed _user,
uint256 _newRateMode,
uint256 _newRate,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a user enables a reserve as collateral
* @param _reserve the address of the reserve
* @param _user the address of the user
**/
event ReserveUsedAsCollateralEnabled(address indexed _reserve, address indexed _user);
/**
* @dev emitted when a user disables a reserve as collateral
* @param _reserve the address of the reserve
* @param _user the address of the user
**/
event ReserveUsedAsCollateralDisabled(address indexed _reserve, address indexed _user);
/**
* @dev emitted when the stable rate of a user gets rebalanced
* @param _reserve the address of the reserve
* @param _user the address of the user for which the rebalance has been executed
* @param _newStableRate the new stable borrow rate after the rebalance
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event RebalanceStableBorrowRate(
address indexed _reserve,
address indexed _user,
uint256 _newStableRate,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a flashloan is executed
* @param _target the address of the flashLoanReceiver
* @param _reserve the address of the reserve
* @param _amount the amount requested
* @param _totalFee the total fee on the amount
* @param _protocolFee the part of the fee for the protocol
* @param _timestamp the timestamp of the action
**/
event FlashLoan(
address indexed _target,
address indexed _reserve,
uint256 _amount,
uint256 _totalFee,
uint256 _protocolFee,
uint256 _timestamp
);
/**
* @dev these events are not emitted directly by the LendingPool
* but they are declared here as the LendingPoolLiquidationManager
* is executed using a delegateCall().
* This allows to have the events in the generated ABI for LendingPool.
**/
/**
* @dev emitted when a borrow fee is liquidated
* @param _collateral the address of the collateral being liquidated
* @param _reserve the address of the reserve
* @param _user the address of the user being liquidated
* @param _feeLiquidated the total fee liquidated
* @param _liquidatedCollateralForFee the amount of collateral received by the protocol in exchange for the fee
* @param _timestamp the timestamp of the action
**/
event OriginationFeeLiquidated(
address indexed _collateral,
address indexed _reserve,
address indexed _user,
uint256 _feeLiquidated,
uint256 _liquidatedCollateralForFee,
uint256 _timestamp
);
/**
* @dev emitted when a borrower is liquidated
* @param _collateral the address of the collateral being liquidated
* @param _reserve the address of the reserve
* @param _user the address of the user being liquidated
* @param _purchaseAmount the total amount liquidated
* @param _liquidatedCollateralAmount the amount of collateral being liquidated
* @param _accruedBorrowInterest the amount of interest accrued by the borrower since the last action
* @param _liquidator the address of the liquidator
* @param _receiveAToken true if the liquidator wants to receive aTokens, false otherwise
* @param _timestamp the timestamp of the action
**/
event LiquidationCall(
address indexed _collateral,
address indexed _reserve,
address indexed _user,
uint256 _purchaseAmount,
uint256 _liquidatedCollateralAmount,
uint256 _accruedBorrowInterest,
address _liquidator,
bool _receiveAToken,
uint256 _timestamp
);
/**
* @dev functions affected by this modifier can only be invoked by the
* aToken.sol contract
* @param _reserve the address of the reserve
**/
modifier onlyOverlyingAToken(address _reserve) {
require(
msg.sender == core.getReserveATokenAddress(_reserve),
"The caller of this function can only be the aToken contract of this reserve"
);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the reserve is active
* @param _reserve the address of the reserve
**/
modifier onlyActiveReserve(address _reserve) {
requireReserveActiveInternal(_reserve);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the reserve is not freezed.
* A freezed reserve only allows redeems, repays, rebalances and liquidations.
* @param _reserve the address of the reserve
**/
modifier onlyUnfreezedReserve(address _reserve) {
requireReserveNotFreezedInternal(_reserve);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the provided _amount input parameter
* is not zero.
* @param _amount the amount provided
**/
modifier onlyAmountGreaterThanZero(uint256 _amount) {
requireAmountGreaterThanZeroInternal(_amount);
_;
}
uint256 public constant UINT_MAX_VALUE = uint256(-1);
uint256 public constant LENDINGPOOL_REVISION = 0x3;
function getRevision() internal pure returns (uint256) {
return LENDINGPOOL_REVISION;
}
/**
* @dev this function is invoked by the proxy contract when the LendingPool contract is added to the
* AddressesProvider.
* @param _addressesProvider the address of the LendingPoolAddressesProvider registry
**/
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
core = LendingPoolCore(addressesProvider.getLendingPoolCore());
dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());
parametersProvider = LendingPoolParametersProvider(
addressesProvider.getLendingPoolParametersProvider()
);
feeProvider = IFeeProvider(addressesProvider.getFeeProvider());
}
/**
* @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens)
* is minted.
* @param _reserve the address of the reserve
* @param _amount the amount to be deposited
* @param _referralCode integrators are assigned a referral code and can potentially receive rewards.
**/
function deposit(address _reserve, uint256 _amount, uint16 _referralCode)
external
payable
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
AToken aToken = AToken(core.getReserveATokenAddress(_reserve));
bool isFirstDeposit = aToken.balanceOf(msg.sender) == 0;
core.updateStateOnDeposit(_reserve, msg.sender, _amount, isFirstDeposit);
//minting AToken to user 1:1 with the specific exchange rate
aToken.mintOnDeposit(msg.sender, _amount);
//transfer to the core contract
core.transferToReserve.value(msg.value)(_reserve, msg.sender, _amount);
//solium-disable-next-line
emit Deposit(_reserve, msg.sender, _amount, _referralCode, block.timestamp);
}
/**
* @dev Redeems the underlying amount of assets requested by _user.
* This function is executed by the overlying aToken contract in response to a redeem action.
* @param _reserve the address of the reserve
* @param _user the address of the user performing the action
* @param _amount the underlying amount to be redeemed
**/
function redeemUnderlying(
address _reserve,
address payable _user,
uint256 _amount,
uint256 _aTokenBalanceAfterRedeem
)
external
nonReentrant
onlyOverlyingAToken(_reserve)
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
uint256 currentAvailableLiquidity = core.getReserveAvailableLiquidity(_reserve);
require(
currentAvailableLiquidity >= _amount,
"There is not enough liquidity available to redeem"
);
core.updateStateOnRedeem(_reserve, _user, _amount, _aTokenBalanceAfterRedeem == 0);
core.transferToUser(_reserve, _user, _amount);
//solium-disable-next-line
emit RedeemUnderlying(_reserve, _user, _amount, block.timestamp);
}
/**
* @dev data structures for local computations in the borrow() method.
*/
struct BorrowLocalVars {
uint256 principalBorrowBalance;
uint256 currentLtv;
uint256 currentLiquidationThreshold;
uint256 borrowFee;
uint256 requestedBorrowAmountETH;
uint256 amountOfCollateralNeededETH;
uint256 userCollateralBalanceETH;
uint256 userBorrowBalanceETH;
uint256 userTotalFeesETH;
uint256 borrowBalanceIncrease;
uint256 currentReserveStableRate;
uint256 availableLiquidity;
uint256 reserveDecimals;
uint256 finalUserBorrowRate;
CoreLibrary.InterestRateMode rateMode;
bool healthFactorBelowThreshold;
}
/**
* @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower
* already deposited enough collateral.
* @param _reserve the address of the reserve
* @param _amount the amount to be borrowed
* @param _interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE)
**/
function borrow(
address _reserve,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode
)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
BorrowLocalVars memory vars;
//check that the reserve is enabled for borrowing
require(core.isReserveBorrowingEnabled(_reserve), "Reserve is not enabled for borrowing");
//validate interest rate mode
require(
uint256(CoreLibrary.InterestRateMode.VARIABLE) == _interestRateMode ||
uint256(CoreLibrary.InterestRateMode.STABLE) == _interestRateMode,
"Invalid interest rate mode selected"
);
//cast the rateMode to coreLibrary.interestRateMode
vars.rateMode = CoreLibrary.InterestRateMode(_interestRateMode);
//check that the amount is available in the reserve
vars.availableLiquidity = core.getReserveAvailableLiquidity(_reserve);
require(
vars.availableLiquidity >= _amount,
"There is not enough liquidity available in the reserve"
);
(
,
vars.userCollateralBalanceETH,
vars.userBorrowBalanceETH,
vars.userTotalFeesETH,
vars.currentLtv,
vars.currentLiquidationThreshold,
,
vars.healthFactorBelowThreshold
) = dataProvider.calculateUserGlobalData(msg.sender);
require(vars.userCollateralBalanceETH > 0, "The collateral balance is 0");
require(
!vars.healthFactorBelowThreshold,
"The borrower can already be liquidated so he cannot borrow more"
);
//calculating fees
vars.borrowFee = feeProvider.calculateLoanOriginationFee(msg.sender, _amount);
require(vars.borrowFee > 0, "The amount to borrow is too small");
vars.amountOfCollateralNeededETH = dataProvider.calculateCollateralNeededInETH(
_reserve,
_amount,
vars.borrowFee,
vars.userBorrowBalanceETH,
vars.userTotalFeesETH,
vars.currentLtv
);
require(
vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,
"There is not enough collateral to cover a new borrow"
);
/**
* Following conditions need to be met if the user is borrowing at a stable rate:
* 1. Reserve must be enabled for stable rate borrowing
* 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency
* they are borrowing, to prevent abuses.
* 3. Users will be able to borrow only a relatively small, configurable amount of the total
* liquidity
**/
if (vars.rateMode == CoreLibrary.InterestRateMode.STABLE) {
//check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve
require(
core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, _amount),
"User cannot borrow the selected amount with a stable rate"
);
//calculate the max available loan size in stable rate mode as a percentage of the
//available liquidity
uint256 maxLoanPercent = parametersProvider.getMaxStableRateBorrowSizePercent();
uint256 maxLoanSizeStable = vars.availableLiquidity.mul(maxLoanPercent).div(100);
require(
_amount <= maxLoanSizeStable,
"User is trying to borrow too much liquidity at a stable rate"
);
}
//all conditions passed - borrow is accepted
(vars.finalUserBorrowRate, vars.borrowBalanceIncrease) = core.updateStateOnBorrow(
_reserve,
msg.sender,
_amount,
vars.borrowFee,
vars.rateMode
);
//if we reached this point, we can transfer
core.transferToUser(_reserve, msg.sender, _amount);
emit Borrow(
_reserve,
msg.sender,
_amount,
_interestRateMode,
vars.finalUserBorrowRate,
vars.borrowFee,
vars.borrowBalanceIncrease,
_referralCode,
//solium-disable-next-line
block.timestamp
);
}
/**
* @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified).
* @dev the target user is defined by _onBehalfOf. If there is no repayment on behalf of another account,
* _onBehalfOf must be equal to msg.sender.
* @param _reserve the address of the reserve on which the user borrowed
* @param _amount the amount to repay, or uint256(-1) if the user wants to repay everything
* @param _onBehalfOf the address for which msg.sender is repaying.
**/
struct RepayLocalVars {
uint256 principalBorrowBalance;
uint256 compoundedBorrowBalance;
uint256 borrowBalanceIncrease;
bool isETH;
uint256 paybackAmount;
uint256 paybackAmountMinusFees;
uint256 currentStableRate;
uint256 originationFee;
}
function repay(address _reserve, uint256 _amount, address payable _onBehalfOf)
external
payable
nonReentrant
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
RepayLocalVars memory vars;
(
vars.principalBorrowBalance,
vars.compoundedBorrowBalance,
vars.borrowBalanceIncrease
) = core.getUserBorrowBalances(_reserve, _onBehalfOf);
vars.originationFee = core.getUserOriginationFee(_reserve, _onBehalfOf);
vars.isETH = EthAddressLib.ethAddress() == _reserve;
require(vars.compoundedBorrowBalance > 0, "The user does not have any borrow pending");
require(
_amount != UINT_MAX_VALUE || msg.sender == _onBehalfOf,
"To repay on behalf of an user an explicit amount to repay is needed."
);
//default to max amount
vars.paybackAmount = vars.compoundedBorrowBalance.add(vars.originationFee);
if (_amount != UINT_MAX_VALUE && _amount < vars.paybackAmount) {
vars.paybackAmount = _amount;
}
require(
!vars.isETH || msg.value >= vars.paybackAmount,
"Invalid msg.value sent for the repayment"
);
//if the amount is smaller than the origination fee, just transfer the amount to the fee destination address
if (vars.paybackAmount <= vars.originationFee) {
core.updateStateOnRepay(
_reserve,
_onBehalfOf,
0,
vars.paybackAmount,
vars.borrowBalanceIncrease,
false
);
core.transferToFeeCollectionAddress.value(vars.isETH ? vars.paybackAmount : 0)(
_reserve,
_onBehalfOf,
vars.paybackAmount,
addressesProvider.getTokenDistributor()
);
emit Repay(
_reserve,
_onBehalfOf,
msg.sender,
0,
vars.paybackAmount,
vars.borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
return;
}
vars.paybackAmountMinusFees = vars.paybackAmount.sub(vars.originationFee);
core.updateStateOnRepay(
_reserve,
_onBehalfOf,
vars.paybackAmountMinusFees,
vars.originationFee,
vars.borrowBalanceIncrease,
vars.compoundedBorrowBalance == vars.paybackAmountMinusFees
);
//if the user didn't repay the origination fee, transfer the fee to the fee collection address
if(vars.originationFee > 0) {
core.transferToFeeCollectionAddress.value(vars.isETH ? vars.originationFee : 0)(
_reserve,
_onBehalfOf,
vars.originationFee,
addressesProvider.getTokenDistributor()
);
}
//sending the total msg.value if the transfer is ETH.
//the transferToReserve() function will take care of sending the
//excess ETH back to the caller
core.transferToReserve.value(vars.isETH ? msg.value.sub(vars.originationFee) : 0)(
_reserve,
msg.sender,
vars.paybackAmountMinusFees
);
emit Repay(
_reserve,
_onBehalfOf,
msg.sender,
vars.paybackAmountMinusFees,
vars.originationFee,
vars.borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
}
/**
* @dev borrowers can user this function to swap between stable and variable borrow rate modes.
* @param _reserve the address of the reserve on which the user borrowed
**/
function swapBorrowRateMode(address _reserve)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
{
(uint256 principalBorrowBalance, uint256 compoundedBorrowBalance, uint256 borrowBalanceIncrease) = core
.getUserBorrowBalances(_reserve, msg.sender);
require(
compoundedBorrowBalance > 0,
"User does not have a borrow in progress on this reserve"
);
CoreLibrary.InterestRateMode currentRateMode = core.getUserCurrentBorrowRateMode(
_reserve,
msg.sender
);
if (currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
/**
* user wants to swap to stable, before swapping we need to ensure that
* 1. stable borrow rate is enabled on the reserve
* 2. user is not trying to abuse the reserve by depositing
* more collateral than he is borrowing, artificially lowering
* the interest rate, borrowing at variable, and switching to stable
**/
require(
core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, compoundedBorrowBalance),
"User cannot borrow the selected amount at stable"
);
}
(CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core
.updateStateOnSwapRate(
_reserve,
msg.sender,
principalBorrowBalance,
compoundedBorrowBalance,
borrowBalanceIncrease,
currentRateMode
);
emit Swap(
_reserve,
msg.sender,
uint256(newRateMode),
newBorrowRate,
borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
}
/**
* @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate.
* this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair
* rate. The rebalance mechanism is updated in the context of the V1 -> V2 transition to automatically switch the user to variable.
* @param _reserve the address of the reserve
* @param _user the address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address _reserve, address _user)
external
nonReentrant
onlyActiveReserve(_reserve)
{
(uint256 principalBalance, uint256 compoundedBalance, uint256 borrowBalanceIncrease) = core.getUserBorrowBalances(
_reserve,
_user
);
//step 1: user must be borrowing on _reserve at a stable rate
require(compoundedBalance > 0, "User does not have any borrow for this reserve");
CoreLibrary.InterestRateMode rateMode = core.getUserCurrentBorrowRateMode(_reserve, _user);
require(
rateMode ==
CoreLibrary.InterestRateMode.STABLE,
"The user borrow is variable and cannot be rebalanced"
);
uint256 userCurrentStableRate = core.getUserCurrentStableBorrowRate(_reserve, _user);
uint256 liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);
if (userCurrentStableRate < liquidityRate) {
(CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core
.updateStateOnSwapRate(
_reserve,
_user,
principalBalance,
compoundedBalance,
borrowBalanceIncrease,
rateMode
);
emit Swap(
_reserve,
_user,
uint256(newRateMode),
newBorrowRate,
borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
}
revert("Interest rate rebalance conditions were not met");
}
/**
* @dev allows depositors to enable or disable a specific deposit as collateral.
* @param _reserve the address of the reserve
* @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise.
**/
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
{
uint256 underlyingBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender);
require(underlyingBalance > 0, "User does not have any liquidity deposited");
require(
dataProvider.balanceDecreaseAllowed(_reserve, msg.sender, underlyingBalance),
"User deposit is already being used as collateral"
);
core.setUserUseReserveAsCollateral(_reserve, msg.sender, _useAsCollateral);
if (_useAsCollateral) {
emit ReserveUsedAsCollateralEnabled(_reserve, msg.sender);
} else {
emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender);
}
}
/**
* @dev users can invoke this function to liquidate an undercollateralized position.
* @param _reserve the address of the collateral to liquidated
* @param _reserve the address of the principal reserve
* @param _user the address of the borrower
* @param _purchaseAmount the amount of principal that the liquidator wants to repay
* @param _receiveAToken true if the liquidators wants to receive the aTokens, false if
* he wants to receive the underlying asset directly
**/
function liquidationCall(
address _collateral,
address _reserve,
address _user,
uint256 _purchaseAmount,
bool _receiveAToken
) external payable nonReentrant onlyActiveReserve(_reserve) onlyActiveReserve(_collateral) {
address liquidationManager = addressesProvider.getLendingPoolLiquidationManager();
//solium-disable-next-line
(bool success, bytes memory result) = liquidationManager.delegatecall(
abi.encodeWithSignature(
"liquidationCall(address,address,address,uint256,bool)",
_collateral,
_reserve,
_user,
_purchaseAmount,
_receiveAToken
)
);
require(success, "Liquidation call failed");
(uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));
if (returnCode != 0) {
//error found
revert(string(abi.encodePacked("Liquidation failed: ", returnMessage)));
}
}
/**
* @dev allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts
* that must be kept into consideration. For further details please visit https://developers.aave.com
* @param _receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface.
* @param _reserve the address of the principal reserve
* @param _amount the amount requested for this flashloan
**/
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes memory _params)
public
nonReentrant
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
//check that the reserve has enough available liquidity
//we avoid using the getAvailableLiquidity() function in LendingPoolCore to save gas
uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress()
? address(core).balance
: IERC20(_reserve).balanceOf(address(core));
require(
availableLiquidityBefore >= _amount,
"There is not enough liquidity available to borrow"
);
(uint256 totalFeeBips, uint256 protocolFeeBips) = parametersProvider
.getFlashLoanFeesInBips();
//calculate amount fee
uint256 amountFee = _amount.mul(totalFeeBips).div(10000);
//protocol fee is the part of the amountFee reserved for the protocol - the rest goes to depositors
uint256 protocolFee = amountFee.mul(protocolFeeBips).div(10000);
require(
amountFee > 0 && protocolFee > 0,
"The requested amount is too small for a flashLoan."
);
//get the FlashLoanReceiver instance
IFlashLoanReceiver receiver = IFlashLoanReceiver(_receiver);
address payable userPayable = address(uint160(_receiver));
//transfer funds to the receiver
core.transferToUser(_reserve, userPayable, _amount);
//execute action of the receiver
receiver.executeOperation(_reserve, _amount, amountFee, _params);
//check that the actual balance of the core contract includes the returned amount
uint256 availableLiquidityAfter = _reserve == EthAddressLib.ethAddress()
? address(core).balance
: IERC20(_reserve).balanceOf(address(core));
require(
availableLiquidityAfter == availableLiquidityBefore.add(amountFee),
"The actual balance of the protocol is inconsistent"
);
core.updateStateOnFlashLoan(
_reserve,
availableLiquidityBefore,
amountFee.sub(protocolFee),
protocolFee
);
//solium-disable-next-line
emit FlashLoan(_receiver, _reserve, _amount, amountFee, protocolFee, block.timestamp);
}
/**
* @dev accessory functions to fetch data from the core contract
**/
function getReserveConfigurationData(address _reserve)
external
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address interestRateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
)
{
return dataProvider.getReserveConfigurationData(_reserve);
}
function getReserveData(address _reserve)
external
view
returns (
uint256 totalLiquidity,
uint256 availableLiquidity,
uint256 totalBorrowsStable,
uint256 totalBorrowsVariable,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 utilizationRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
address aTokenAddress,
uint40 lastUpdateTimestamp
)
{
return dataProvider.getReserveData(_reserve);
}
function getUserAccountData(address _user)
external
view
returns (
uint256 totalLiquidityETH,
uint256 totalCollateralETH,
uint256 totalBorrowsETH,
uint256 totalFeesETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
return dataProvider.getUserAccountData(_user);
}
function getUserReserveData(address _reserve, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentBorrowBalance,
uint256 principalBorrowBalance,
uint256 borrowRateMode,
uint256 borrowRate,
uint256 liquidityRate,
uint256 originationFee,
uint256 variableBorrowIndex,
uint256 lastUpdateTimestamp,
bool usageAsCollateralEnabled
)
{
return dataProvider.getUserReserveData(_reserve, _user);
}
function getReserves() external view returns (address[] memory) {
return core.getReserves();
}
/**
* @dev internal function to save on code size for the onlyActiveReserve modifier
**/
function requireReserveActiveInternal(address _reserve) internal view {
require(core.getReserveIsActive(_reserve), "Action requires an active reserve");
}
/**
* @notice internal function to save on code size for the onlyUnfreezedReserve modifier
**/
function requireReserveNotFreezedInternal(address _reserve) internal view {
require(!core.getReserveIsFreezed(_reserve), "Action requires an unfreezed reserve");
}
/**
* @notice internal function to save on code size for the onlyAmountGreaterThanZero modifier
**/
function requireAmountGreaterThanZeroInternal(uint256 _amount) internal pure {
require(_amount > 0, "Amount must be greater than 0");
}
}
/**
* @title LendingPoolCore contract
* @author Aave
* @notice Holds the state of the lending pool and all the funds deposited
* @dev NOTE: The core does not enforce security checks on the update of the state
* (eg, updateStateOnBorrow() does not enforce that borrowed is enabled on the reserve).
* The check that an action can be performed is a duty of the overlying LendingPool contract.
**/
contract LendingPoolCore is VersionedInitializable {
using SafeMath for uint256;
using WadRayMath for uint256;
using CoreLibrary for CoreLibrary.ReserveData;
using CoreLibrary for CoreLibrary.UserReserveData;
using SafeERC20 for ERC20;
using Address for address payable;
/**
* @dev Emitted when the state of a reserve is updated
* @param reserve the address of the reserve
* @param liquidityRate the new liquidity rate
* @param stableBorrowRate the new stable borrow rate
* @param variableBorrowRate the new variable borrow rate
* @param liquidityIndex the new liquidity index
* @param variableBorrowIndex the new variable borrow index
**/
event ReserveUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
address public lendingPoolAddress;
LendingPoolAddressesProvider public addressesProvider;
/**
* @dev only lending pools can use functions affected by this modifier
**/
modifier onlyLendingPool {
require(lendingPoolAddress == msg.sender, "The caller must be a lending pool contract");
_;
}
/**
* @dev only lending pools configurator can use functions affected by this modifier
**/
modifier onlyLendingPoolConfigurator {
require(
addressesProvider.getLendingPoolConfigurator() == msg.sender,
"The caller must be a lending pool configurator contract"
);
_;
}
mapping(address => CoreLibrary.ReserveData) internal reserves;
mapping(address => mapping(address => CoreLibrary.UserReserveData)) internal usersReserveData;
address[] public reservesList;
uint256 public constant CORE_REVISION = 0x7;
/**
* @dev returns the revision number of the contract
**/
function getRevision() internal pure returns (uint256) {
return CORE_REVISION;
}
/**
* @dev initializes the Core contract, invoked upon registration on the AddressesProvider
* @param _addressesProvider the addressesProvider contract
**/
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
refreshConfigInternal();
}
/**
* @dev updates the state of the core as a result of a deposit action
* @param _reserve the address of the reserve in which the deposit is happening
* @param _user the address of the the user depositing
* @param _amount the amount being deposited
* @param _isFirstDeposit true if the user is depositing for the first time
**/
function updateStateOnDeposit(
address _reserve,
address _user,
uint256 _amount,
bool _isFirstDeposit
) external onlyLendingPool {
reserves[_reserve].updateCumulativeIndexes();
updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0);
if (_isFirstDeposit) {
//if this is the first deposit of the user, we configure the deposit as enabled to be used as collateral
setUserUseReserveAsCollateral(_reserve, _user, true);
}
}
/**
* @dev updates the state of the core as a result of a redeem action
* @param _reserve the address of the reserve in which the redeem is happening
* @param _user the address of the the user redeeming
* @param _amountRedeemed the amount being redeemed
* @param _userRedeemedEverything true if the user is redeeming everything
**/
function updateStateOnRedeem(
address _reserve,
address _user,
uint256 _amountRedeemed,
bool _userRedeemedEverything
) external onlyLendingPool {
//compound liquidity and variable borrow interests
reserves[_reserve].updateCumulativeIndexes();
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed);
//if user redeemed everything the useReserveAsCollateral flag is reset
if (_userRedeemedEverything) {
setUserUseReserveAsCollateral(_reserve, _user, false);
}
}
/**
* @dev updates the state of the core as a result of a flashloan action
* @param _reserve the address of the reserve in which the flashloan is happening
* @param _income the income of the protocol as a result of the action
**/
function updateStateOnFlashLoan(
address _reserve,
uint256 _availableLiquidityBefore,
uint256 _income,
uint256 _protocolFee
) external onlyLendingPool {
transferFlashLoanProtocolFeeInternal(_reserve, _protocolFee);
//compounding the cumulated interest
reserves[_reserve].updateCumulativeIndexes();
uint256 totalLiquidityBefore = _availableLiquidityBefore.add(
getReserveTotalBorrows(_reserve)
);
//compounding the received fee into the reserve
reserves[_reserve].cumulateToLiquidityIndex(totalLiquidityBefore, _income);
//refresh interest rates
updateReserveInterestRatesAndTimestampInternal(_reserve, _income, 0);
}
/**
* @dev updates the state of the core as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _amountBorrowed the new amount borrowed
* @param _borrowFee the fee on the amount borrowed
* @param _rateMode the borrow rate mode (stable, variable)
* @return the new borrow rate for the user
**/
function updateStateOnBorrow(
address _reserve,
address _user,
uint256 _amountBorrowed,
uint256 _borrowFee,
CoreLibrary.InterestRateMode _rateMode
) external onlyLendingPool returns (uint256, uint256) {
// getting the previous borrow data of the user
(uint256 principalBorrowBalance, , uint256 balanceIncrease) = getUserBorrowBalances(
_reserve,
_user
);
updateReserveStateOnBorrowInternal(
_reserve,
_user,
principalBorrowBalance,
balanceIncrease,
_amountBorrowed,
_rateMode
);
updateUserStateOnBorrowInternal(
_reserve,
_user,
_amountBorrowed,
balanceIncrease,
_borrowFee,
_rateMode
);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed);
return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease);
}
/**
* @dev updates the state of the core as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _originationFeeRepaid the fee on the amount that is being repaid
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _repaidWholeLoan true if the user is repaying the whole loan
**/
function updateStateOnRepay(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _originationFeeRepaid,
uint256 _balanceIncrease,
bool _repaidWholeLoan
) external onlyLendingPool {
updateReserveStateOnRepayInternal(
_reserve,
_user,
_paybackAmountMinusFees,
_balanceIncrease
);
updateUserStateOnRepayInternal(
_reserve,
_user,
_paybackAmountMinusFees,
_originationFeeRepaid,
_balanceIncrease,
_repaidWholeLoan
);
updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0);
}
/**
* @dev updates the state of the core as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _principalBorrowBalance the amount borrowed by the user
* @param _compoundedBorrowBalance the amount borrowed plus accrued interest
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _currentRateMode the current interest rate mode for the user
**/
function updateStateOnSwapRate(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _compoundedBorrowBalance,
uint256 _balanceIncrease,
CoreLibrary.InterestRateMode _currentRateMode
) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) {
updateReserveStateOnSwapRateInternal(
_reserve,
_user,
_principalBorrowBalance,
_compoundedBorrowBalance,
_currentRateMode
);
CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal(
_reserve,
_user,
_balanceIncrease,
_currentRateMode
);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);
return (newRateMode, getUserCurrentBorrowRate(_reserve, _user));
}
/**
* @dev updates the state of the core as a consequence of a liquidation action.
* @param _principalReserve the address of the principal reserve that is being repaid
* @param _collateralReserve the address of the collateral reserve that is being liquidated
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _collateralToLiquidate the amount of collateral being liquidated
* @param _feeLiquidated the amount of origination fee being liquidated
* @param _liquidatedCollateralForFee the amount of collateral equivalent to the origination fee + bonus
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _liquidatorReceivesAToken true if the liquidator will receive aTokens, false otherwise
**/
function updateStateOnLiquidation(
address _principalReserve,
address _collateralReserve,
address _user,
uint256 _amountToLiquidate,
uint256 _collateralToLiquidate,
uint256 _feeLiquidated,
uint256 _liquidatedCollateralForFee,
uint256 _balanceIncrease,
bool _liquidatorReceivesAToken
) external onlyLendingPool {
updatePrincipalReserveStateOnLiquidationInternal(
_principalReserve,
_user,
_amountToLiquidate,
_balanceIncrease
);
updateCollateralReserveStateOnLiquidationInternal(
_collateralReserve
);
updateUserStateOnLiquidationInternal(
_principalReserve,
_user,
_amountToLiquidate,
_feeLiquidated,
_balanceIncrease
);
updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0);
if (!_liquidatorReceivesAToken) {
updateReserveInterestRatesAndTimestampInternal(
_collateralReserve,
0,
_collateralToLiquidate.add(_liquidatedCollateralForFee)
);
}
}
/**
* @dev updates the state of the core as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @return the new stable rate for the user
**/
function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease)
external
onlyLendingPool
returns (uint256)
{
updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);
//update user data and rebalance the rate
updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);
return usersReserveData[_user][_reserve].stableBorrowRate;
}
/**
* @dev enables or disables a reserve as collateral
* @param _reserve the address of the principal reserve where the user deposited
* @param _user the address of the depositor
* @param _useAsCollateral true if the depositor wants to use the reserve as collateral
**/
function setUserUseReserveAsCollateral(address _reserve, address _user, bool _useAsCollateral)
public
onlyLendingPool
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
user.useAsCollateral = _useAsCollateral;
}
/**
* @notice ETH/token transfer functions
**/
/**
* @dev fallback function enforces that the caller is a contract, to support flashloan transfers
**/
function() external payable {
//only contracts can send ETH to the core
require(msg.sender.isContract(), "Only contracts can send ether to the Lending pool core");
}
/**
* @dev transfers to the user a specific amount from the reserve.
* @param _reserve the address of the reserve where the transfer is happening
* @param _user the address of the user receiving the transfer
* @param _amount the amount being transferred
**/
function transferToUser(address _reserve, address payable _user, uint256 _amount)
external
onlyLendingPool
{
if (_reserve != EthAddressLib.ethAddress()) {
ERC20(_reserve).safeTransfer(_user, _amount);
} else {
//solium-disable-next-line
(bool result, ) = _user.call.value(_amount).gas(50000)("");
require(result, "Transfer of ETH failed");
}
}
/**
* @dev transfers the protocol fees to the fees collection address
* @param _token the address of the token being transferred
* @param _user the address of the user from where the transfer is happening
* @param _amount the amount being transferred
* @param _destination the fee receiver address
**/
function transferToFeeCollectionAddress(
address _token,
address _user,
uint256 _amount,
address _destination
) external payable onlyLendingPool {
address payable feeAddress = address(uint160(_destination)); //cast the address to payable
if (_token != EthAddressLib.ethAddress()) {
require(
msg.value == 0,
"User is sending ETH along with the ERC20 transfer. Check the value attribute of the transaction"
);
ERC20(_token).safeTransferFrom(_user, feeAddress, _amount);
} else {
require(msg.value >= _amount, "The amount and the value sent to deposit do not match");
//solium-disable-next-line
(bool result, ) = feeAddress.call.value(_amount).gas(50000)("");
require(result, "Transfer of ETH failed");
}
}
/**
* @dev transfers the fees to the fees collection address in the case of liquidation
* @param _token the address of the token being transferred
* @param _amount the amount being transferred
* @param _destination the fee receiver address
**/
function liquidateFee(
address _token,
uint256 _amount,
address _destination
) external payable onlyLendingPool {
address payable feeAddress = address(uint160(_destination)); //cast the address to payable
require(
msg.value == 0,
"Fee liquidation does not require any transfer of value"
);
if (_token != EthAddressLib.ethAddress()) {
ERC20(_token).safeTransfer(feeAddress, _amount);
} else {
//solium-disable-next-line
(bool result, ) = feeAddress.call.value(_amount).gas(50000)("");
require(result, "Transfer of ETH failed");
}
}
/**
* @dev transfers an amount from a user to the destination reserve
* @param _reserve the address of the reserve where the amount is being transferred
* @param _user the address of the user from where the transfer is happening
* @param _amount the amount being transferred
**/
function transferToReserve(address _reserve, address payable _user, uint256 _amount)
external
payable
onlyLendingPool
{
if (_reserve != EthAddressLib.ethAddress()) {
require(msg.value == 0, "User is sending ETH along with the ERC20 transfer.");
ERC20(_reserve).safeTransferFrom(_user, address(this), _amount);
} else {
require(msg.value >= _amount, "The amount and the value sent to deposit do not match");
if (msg.value > _amount) {
//send back excess ETH
uint256 excessAmount = msg.value.sub(_amount);
//solium-disable-next-line
(bool result, ) = _user.call.value(excessAmount).gas(50000)("");
require(result, "Transfer of ETH failed");
}
}
}
/**
* @notice data access functions
**/
/**
* @dev returns the basic data (balances, fee accrued, reserve enabled/disabled as collateral)
* needed to calculate the global account data in the LendingPoolDataProvider
* @param _reserve the address of the reserve
* @param _user the address of the user
* @return the user deposited balance, the principal borrow balance, the fee, and if the reserve is enabled as collateral or not
**/
function getUserBasicReserveData(address _reserve, address _user)
external
view
returns (uint256, uint256, uint256, bool)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user);
if (user.principalBorrowBalance == 0) {
return (underlyingBalance, 0, 0, user.useAsCollateral);
}
return (
underlyingBalance,
user.getCompoundedBorrowBalance(reserve),
user.originationFee,
user.useAsCollateral
);
}
/**
* @dev checks if a user is allowed to borrow at a stable rate
* @param _reserve the reserve address
* @param _user the user
* @param _amount the amount the the user wants to borrow
* @return true if the user is allowed to borrow at a stable rate, false otherwise
**/
function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount)
external
view
returns (bool)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (!reserve.isStableBorrowRateEnabled) return false;
return
!user.useAsCollateral ||
!reserve.usageAsCollateralEnabled ||
_amount > getUserUnderlyingAssetBalance(_reserve, _user);
}
/**
* @dev gets the underlying asset balance of a user based on the corresponding aToken balance.
* @param _reserve the reserve address
* @param _user the user address
* @return the underlying deposit balance of the user
**/
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public
view
returns (uint256)
{
AToken aToken = AToken(reserves[_reserve].aTokenAddress);
return aToken.balanceOf(_user);
}
/**
* @dev gets the interest rate strategy contract address for the reserve
* @param _reserve the reserve address
* @return the address of the interest rate strategy contract
**/
function getReserveInterestRateStrategyAddress(address _reserve) public view returns (address) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.interestRateStrategyAddress;
}
/**
* @dev gets the aToken contract address for the reserve
* @param _reserve the reserve address
* @return the address of the aToken contract
**/
function getReserveATokenAddress(address _reserve) public view returns (address) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.aTokenAddress;
}
/**
* @dev gets the available liquidity in the reserve. The available liquidity is the balance of the core contract
* @param _reserve the reserve address
* @return the available liquidity
**/
function getReserveAvailableLiquidity(address _reserve) public view returns (uint256) {
uint256 balance = 0;
if (_reserve == EthAddressLib.ethAddress()) {
balance = address(this).balance;
} else {
balance = IERC20(_reserve).balanceOf(address(this));
}
return balance;
}
/**
* @dev gets the total liquidity in the reserve. The total liquidity is the balance of the core contract + total borrows
* @param _reserve the reserve address
* @return the total liquidity
**/
function getReserveTotalLiquidity(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return getReserveAvailableLiquidity(_reserve).add(reserve.getTotalBorrows());
}
/**
* @dev gets the normalized income of the reserve. a value of 1e27 means there is no income. A value of 2e27 means there
* there has been 100% income.
* @param _reserve the reserve address
* @return the reserve normalized income
**/
function getReserveNormalizedIncome(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.getNormalizedIncome();
}
/**
* @dev gets the reserve total borrows
* @param _reserve the reserve address
* @return the total borrows (stable + variable)
**/
function getReserveTotalBorrows(address _reserve) public view returns (uint256) {
return reserves[_reserve].getTotalBorrows();
}
/**
* @dev gets the reserve total borrows stable
* @param _reserve the reserve address
* @return the total borrows stable
**/
function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.totalBorrowsStable;
}
/**
* @dev gets the reserve total borrows variable
* @param _reserve the reserve address
* @return the total borrows variable
**/
function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.totalBorrowsVariable;
}
/**
* @dev gets the reserve liquidation threshold
* @param _reserve the reserve address
* @return the reserve liquidation threshold
**/
function getReserveLiquidationThreshold(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.liquidationThreshold;
}
/**
* @dev gets the reserve liquidation bonus
* @param _reserve the reserve address
* @return the reserve liquidation bonus
**/
function getReserveLiquidationBonus(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.liquidationBonus;
}
/**
* @dev gets the reserve current variable borrow rate. Is the base variable borrow rate if the reserve is empty
* @param _reserve the reserve address
* @return the reserve current variable borrow rate
**/
function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
if (reserve.currentVariableBorrowRate == 0) {
return
IReserveInterestRateStrategy(reserve.interestRateStrategyAddress)
.getBaseVariableBorrowRate();
}
return reserve.currentVariableBorrowRate;
}
/**
* @dev gets the reserve current stable borrow rate. Is the market rate if the reserve is empty
* @param _reserve the reserve address
* @return the reserve current stable borrow rate
**/
function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle());
if (reserve.currentStableBorrowRate == 0) {
//no stable rate borrows yet
return oracle.getMarketBorrowRate(_reserve);
}
return reserve.currentStableBorrowRate;
}
/**
* @dev gets the reserve average stable borrow rate. The average stable rate is the weighted average
* of all the loans taken at stable rate.
* @param _reserve the reserve address
* @return the reserve current average borrow rate
**/
function getReserveCurrentAverageStableBorrowRate(address _reserve)
external
view
returns (uint256)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.currentAverageStableBorrowRate;
}
/**
* @dev gets the reserve liquidity rate
* @param _reserve the reserve address
* @return the reserve liquidity rate
**/
function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.currentLiquidityRate;
}
/**
* @dev gets the reserve liquidity cumulative index
* @param _reserve the reserve address
* @return the reserve liquidity cumulative index
**/
function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.lastLiquidityCumulativeIndex;
}
/**
* @dev gets the reserve variable borrow index
* @param _reserve the reserve address
* @return the reserve variable borrow index
**/
function getReserveVariableBorrowsCumulativeIndex(address _reserve)
external
view
returns (uint256)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.lastVariableBorrowCumulativeIndex;
}
/**
* @dev this function aggregates the configuration parameters of the reserve.
* It's used in the LendingPoolDataProvider specifically to save gas, and avoid
* multiple external contract calls to fetch the same data.
* @param _reserve the reserve address
* @return the reserve decimals
* @return the base ltv as collateral
* @return the liquidation threshold
* @return if the reserve is used as collateral or not
**/
function getReserveConfiguration(address _reserve)
external
view
returns (uint256, uint256, uint256, bool)
{
uint256 decimals;
uint256 baseLTVasCollateral;
uint256 liquidationThreshold;
bool usageAsCollateralEnabled;
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
decimals = reserve.decimals;
baseLTVasCollateral = reserve.baseLTVasCollateral;
liquidationThreshold = reserve.liquidationThreshold;
usageAsCollateralEnabled = reserve.usageAsCollateralEnabled;
return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled);
}
/**
* @dev returns the decimals of the reserve
* @param _reserve the reserve address
* @return the reserve decimals
**/
function getReserveDecimals(address _reserve) external view returns (uint256) {
return reserves[_reserve].decimals;
}
/**
* @dev returns true if the reserve is enabled for borrowing
* @param _reserve the reserve address
* @return true if the reserve is enabled for borrowing, false otherwise
**/
function isReserveBorrowingEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.borrowingEnabled;
}
/**
* @dev returns true if the reserve is enabled as collateral
* @param _reserve the reserve address
* @return true if the reserve is enabled as collateral, false otherwise
**/
function isReserveUsageAsCollateralEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.usageAsCollateralEnabled;
}
/**
* @dev returns true if the stable rate is enabled on reserve
* @param _reserve the reserve address
* @return true if the stable rate is enabled on reserve, false otherwise
**/
function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isStableBorrowRateEnabled;
}
/**
* @dev returns true if the reserve is active
* @param _reserve the reserve address
* @return true if the reserve is active, false otherwise
**/
function getReserveIsActive(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isActive;
}
/**
* @notice returns if a reserve is freezed
* @param _reserve the reserve for which the information is needed
* @return true if the reserve is freezed, false otherwise
**/
function getReserveIsFreezed(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isFreezed;
}
/**
* @notice returns the timestamp of the last action on the reserve
* @param _reserve the reserve for which the information is needed
* @return the last updated timestamp of the reserve
**/
function getReserveLastUpdate(address _reserve) external view returns (uint40 timestamp) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
timestamp = reserve.lastUpdateTimestamp;
}
/**
* @dev returns the utilization rate U of a specific reserve
* @param _reserve the reserve for which the information is needed
* @return the utilization rate in ray
**/
function getReserveUtilizationRate(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
uint256 totalBorrows = reserve.getTotalBorrows();
if (totalBorrows == 0) {
return 0;
}
uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve);
return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows));
}
/**
* @return the array of reserves configured on the core
**/
function getReserves() external view returns (address[] memory) {
return reservesList;
}
/**
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return true if the user has chosen to use the reserve as collateral, false otherwise
**/
function isUserUseReserveAsCollateralEnabled(address _reserve, address _user)
external
view
returns (bool)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.useAsCollateral;
}
/**
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the origination fee for the user
**/
function getUserOriginationFee(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.originationFee;
}
/**
* @dev users with no loans in progress have NONE as borrow rate mode
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the borrow rate mode for the user,
**/
function getUserCurrentBorrowRateMode(address _reserve, address _user)
public
view
returns (CoreLibrary.InterestRateMode)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (user.principalBorrowBalance == 0) {
return CoreLibrary.InterestRateMode.NONE;
}
return
user.stableBorrowRate > 0
? CoreLibrary.InterestRateMode.STABLE
: CoreLibrary.InterestRateMode.VARIABLE;
}
/**
* @dev gets the current borrow rate of the user
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the borrow rate for the user,
**/
function getUserCurrentBorrowRate(address _reserve, address _user)
internal
view
returns (uint256)
{
CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user);
if (rateMode == CoreLibrary.InterestRateMode.NONE) {
return 0;
}
return
rateMode == CoreLibrary.InterestRateMode.STABLE
? usersReserveData[_user][_reserve].stableBorrowRate
: reserves[_reserve].currentVariableBorrowRate;
}
/**
* @dev the stable rate returned is 0 if the user is borrowing at variable or not borrowing at all
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the user stable rate
**/
function getUserCurrentStableBorrowRate(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.stableBorrowRate;
}
/**
* @dev calculates and returns the borrow balances of the user
* @param _reserve the address of the reserve
* @param _user the address of the user
* @return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance
**/
function getUserBorrowBalances(address _reserve, address _user)
public
view
returns (uint256, uint256, uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (user.principalBorrowBalance == 0) {
return (0, 0, 0);
}
uint256 principal = user.principalBorrowBalance;
uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance(
user,
reserves[_reserve]
);
return (principal, compoundedBalance, compoundedBalance.sub(principal));
}
/**
* @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the variable borrow index for the user
**/
function getUserVariableBorrowCumulativeIndex(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.lastVariableBorrowCumulativeIndex;
}
/**
* @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the variable borrow index for the user
**/
function getUserLastUpdate(address _reserve, address _user)
external
view
returns (uint256 timestamp)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
timestamp = user.lastUpdateTimestamp;
}
/**
* @dev updates the lending pool core configuration
**/
function refreshConfiguration() external onlyLendingPoolConfigurator {
refreshConfigInternal();
}
/**
* @dev initializes a reserve
* @param _reserve the address of the reserve
* @param _aTokenAddress the address of the overlying aToken contract
* @param _decimals the decimals of the reserve currency
* @param _interestRateStrategyAddress the address of the interest rate strategy contract
**/
function initReserve(
address _reserve,
address _aTokenAddress,
uint256 _decimals,
address _interestRateStrategyAddress
) external onlyLendingPoolConfigurator {
reserves[_reserve].init(_aTokenAddress, _decimals, _interestRateStrategyAddress);
addReserveToListInternal(_reserve);
}
/**
* @dev removes the last added reserve in the reservesList array
* @param _reserveToRemove the address of the reserve
**/
function removeLastAddedReserve(address _reserveToRemove)
external onlyLendingPoolConfigurator {
address lastReserve = reservesList[reservesList.length-1];
require(lastReserve == _reserveToRemove, "Reserve being removed is different than the reserve requested");
//as we can't check if totalLiquidity is 0 (since the reserve added might not be an ERC20) we at least check that there is nothing borrowed
require(getReserveTotalBorrows(lastReserve) == 0, "Cannot remove a reserve with liquidity deposited");
reserves[lastReserve].isActive = false;
reserves[lastReserve].aTokenAddress = address(0);
reserves[lastReserve].decimals = 0;
reserves[lastReserve].lastLiquidityCumulativeIndex = 0;
reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0;
reserves[lastReserve].borrowingEnabled = false;
reserves[lastReserve].usageAsCollateralEnabled = false;
reserves[lastReserve].baseLTVasCollateral = 0;
reserves[lastReserve].liquidationThreshold = 0;
reserves[lastReserve].liquidationBonus = 0;
reserves[lastReserve].interestRateStrategyAddress = address(0);
reservesList.pop();
}
/**
* @dev updates the address of the interest rate strategy contract
* @param _reserve the address of the reserve
* @param _rateStrategyAddress the address of the interest rate strategy contract
**/
function setReserveInterestRateStrategyAddress(address _reserve, address _rateStrategyAddress)
external
onlyLendingPoolConfigurator
{
reserves[_reserve].interestRateStrategyAddress = _rateStrategyAddress;
}
/**
* @dev enables borrowing on a reserve. Also sets the stable rate borrowing
* @param _reserve the address of the reserve
* @param _stableBorrowRateEnabled true if the stable rate needs to be enabled, false otherwise
**/
function enableBorrowingOnReserve(address _reserve, bool _stableBorrowRateEnabled)
external
onlyLendingPoolConfigurator
{
reserves[_reserve].enableBorrowing(_stableBorrowRateEnabled);
}
/**
* @dev disables borrowing on a reserve
* @param _reserve the address of the reserve
**/
function disableBorrowingOnReserve(address _reserve) external onlyLendingPoolConfigurator {
reserves[_reserve].disableBorrowing();
}
/**
* @dev enables a reserve to be used as collateral
* @param _reserve the address of the reserve
**/
function enableReserveAsCollateral(
address _reserve,
uint256 _baseLTVasCollateral,
uint256 _liquidationThreshold,
uint256 _liquidationBonus
) external onlyLendingPoolConfigurator {
reserves[_reserve].enableAsCollateral(
_baseLTVasCollateral,
_liquidationThreshold,
_liquidationBonus
);
}
/**
* @dev disables a reserve to be used as collateral
* @param _reserve the address of the reserve
**/
function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator {
reserves[_reserve].disableAsCollateral();
}
/**
* @dev enable the stable borrow rate mode on a reserve
* @param _reserve the address of the reserve
**/
function enableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isStableBorrowRateEnabled = true;
}
/**
* @dev disable the stable borrow rate mode on a reserve
* @param _reserve the address of the reserve
**/
function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isStableBorrowRateEnabled = false;
}
/**
* @dev activates a reserve
* @param _reserve the address of the reserve
**/
function activateReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
require(
reserve.lastLiquidityCumulativeIndex > 0 &&
reserve.lastVariableBorrowCumulativeIndex > 0,
"Reserve has not been initialized yet"
);
reserve.isActive = true;
}
/**
* @dev deactivates a reserve
* @param _reserve the address of the reserve
**/
function deactivateReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isActive = false;
}
/**
* @notice allows the configurator to freeze the reserve.
* A freezed reserve does not allow any action apart from repay, redeem, liquidationCall, rebalance.
* @param _reserve the address of the reserve
**/
function freezeReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isFreezed = true;
}
/**
* @notice allows the configurator to unfreeze the reserve. A unfreezed reserve allows any action to be executed.
* @param _reserve the address of the reserve
**/
function unfreezeReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isFreezed = false;
}
/**
* @notice allows the configurator to update the loan to value of a reserve
* @param _reserve the address of the reserve
* @param _ltv the new loan to value
**/
function setReserveBaseLTVasCollateral(address _reserve, uint256 _ltv)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.baseLTVasCollateral = _ltv;
}
/**
* @notice allows the configurator to update the liquidation threshold of a reserve
* @param _reserve the address of the reserve
* @param _threshold the new liquidation threshold
**/
function setReserveLiquidationThreshold(address _reserve, uint256 _threshold)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.liquidationThreshold = _threshold;
}
/**
* @notice allows the configurator to update the liquidation bonus of a reserve
* @param _reserve the address of the reserve
* @param _bonus the new liquidation bonus
**/
function setReserveLiquidationBonus(address _reserve, uint256 _bonus)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.liquidationBonus = _bonus;
}
/**
* @notice allows the configurator to update the reserve decimals
* @param _reserve the address of the reserve
* @param _decimals the decimals of the reserve
**/
function setReserveDecimals(address _reserve, uint256 _decimals)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.decimals = _decimals;
}
/**
* @notice internal functions
**/
/**
* @dev updates the state of a reserve as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _principalBorrowBalance the previous borrow balance of the borrower before the action
* @param _balanceIncrease the accrued interest of the user on the previous borrowed amount
* @param _amountBorrowed the new amount borrowed
* @param _rateMode the borrow rate mode (stable, variable)
**/
function updateReserveStateOnBorrowInternal(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _balanceIncrease,
uint256 _amountBorrowed,
CoreLibrary.InterestRateMode _rateMode
) internal {
reserves[_reserve].updateCumulativeIndexes();
//increasing reserve total borrows to account for the new borrow balance of the user
//NOTE: Depending on the previous borrow mode, the borrows might need to be switched from variable to stable or vice versa
updateReserveTotalBorrowsByRateModeInternal(
_reserve,
_user,
_principalBorrowBalance,
_balanceIncrease,
_amountBorrowed,
_rateMode
);
}
/**
* @dev updates the state of a user as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _amountBorrowed the amount borrowed
* @param _balanceIncrease the accrued interest of the user on the previous borrowed amount
* @param _rateMode the borrow rate mode (stable, variable)
* @return the final borrow rate for the user. Emitted by the borrow() event
**/
function updateUserStateOnBorrowInternal(
address _reserve,
address _user,
uint256 _amountBorrowed,
uint256 _balanceIncrease,
uint256 _fee,
CoreLibrary.InterestRateMode _rateMode
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (_rateMode == CoreLibrary.InterestRateMode.STABLE) {
//stable
//reset the user variable index, and update the stable rate
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
} else if (_rateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//variable
//reset the user stable rate, and store the new borrow index
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
} else {
revert("Invalid borrow rate mode");
}
//increase the principal borrows and the origination fee
user.principalBorrowBalance = user.principalBorrowBalance.add(_amountBorrowed).add(
_balanceIncrease
);
user.originationFee = user.originationFee.add(_fee);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the reserve as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateReserveStateOnRepayInternal(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user);
//update the indexes
reserves[_reserve].updateCumulativeIndexes();
//compound the cumulated interest to the borrow balance and then subtracting the payback amount
if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_paybackAmountMinusFees,
user.stableBorrowRate
);
} else {
reserve.increaseTotalBorrowsVariable(_balanceIncrease);
reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees);
}
}
/**
* @dev updates the state of the user as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _originationFeeRepaid the fee on the amount that is being repaid
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _repaidWholeLoan true if the user is repaying the whole loan
**/
function updateUserStateOnRepayInternal(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _originationFeeRepaid,
uint256 _balanceIncrease,
bool _repaidWholeLoan
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
//update the user principal borrow balance, adding the cumulated interest and then subtracting the payback amount
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub(
_paybackAmountMinusFees
);
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
//if the balance decrease is equal to the previous principal (user is repaying the whole loan)
//and the rate mode is stable, we reset the interest rate mode of the user
if (_repaidWholeLoan) {
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = 0;
}
user.originationFee = user.originationFee.sub(_originationFeeRepaid);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the user as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is performing the rate swap
* @param _user the address of the borrower
* @param _principalBorrowBalance the the principal amount borrowed by the user
* @param _compoundedBorrowBalance the principal amount plus the accrued interest
* @param _currentRateMode the rate mode at which the user borrowed
**/
function updateReserveStateOnSwapRateInternal(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _compoundedBorrowBalance,
CoreLibrary.InterestRateMode _currentRateMode
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
//compounding reserve indexes
reserve.updateCumulativeIndexes();
if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {
uint256 userCurrentStableRate = user.stableBorrowRate;
//swap to variable
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_principalBorrowBalance,
userCurrentStableRate
); //decreasing stable from old principal balance
reserve.increaseTotalBorrowsVariable(_compoundedBorrowBalance); //increase variable borrows
} else if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//swap to stable
uint256 currentStableRate = reserve.currentStableBorrowRate;
reserve.decreaseTotalBorrowsVariable(_principalBorrowBalance);
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_compoundedBorrowBalance,
currentStableRate
);
} else {
revert("Invalid rate mode received");
}
}
/**
* @dev updates the state of the user as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is performing the swap
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _currentRateMode the current rate mode of the user
**/
function updateUserStateOnSwapRateInternal(
address _reserve,
address _user,
uint256 _balanceIncrease,
CoreLibrary.InterestRateMode _currentRateMode
) internal returns (CoreLibrary.InterestRateMode) {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE;
if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//switch to stable
newMode = CoreLibrary.InterestRateMode.STABLE;
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
} else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {
newMode = CoreLibrary.InterestRateMode.VARIABLE;
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
} else {
revert("Invalid interest rate mode received");
}
//compounding cumulated interest
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
return newMode;
}
/**
* @dev updates the state of the principal reserve as a consequence of a liquidation action.
* @param _principalReserve the address of the principal reserve that is being repaid
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updatePrincipalReserveStateOnLiquidationInternal(
address _principalReserve,
address _user,
uint256 _amountToLiquidate,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_principalReserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve];
//update principal reserve data
reserve.updateCumulativeIndexes();
CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(
_principalReserve,
_user
);
if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
//increase the total borrows by the compounded interest
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
//decrease by the actual amount to liquidate
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_amountToLiquidate,
user.stableBorrowRate
);
} else {
//increase the total borrows by the compounded interest
reserve.increaseTotalBorrowsVariable(_balanceIncrease);
//decrease by the actual amount to liquidate
reserve.decreaseTotalBorrowsVariable(_amountToLiquidate);
}
}
/**
* @dev updates the state of the collateral reserve as a consequence of a liquidation action.
* @param _collateralReserve the address of the collateral reserve that is being liquidated
**/
function updateCollateralReserveStateOnLiquidationInternal(
address _collateralReserve
) internal {
//update collateral reserve
reserves[_collateralReserve].updateCumulativeIndexes();
}
/**
* @dev updates the state of the user being liquidated as a consequence of a liquidation action.
* @param _reserve the address of the principal reserve that is being repaid
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _feeLiquidated the amount of origination fee being liquidated
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateUserStateOnLiquidationInternal(
address _reserve,
address _user,
uint256 _amountToLiquidate,
uint256 _feeLiquidated,
uint256 _balanceIncrease
) internal {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
//first increase by the compounded interest, then decrease by the liquidated amount
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub(
_amountToLiquidate
);
if (
getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.VARIABLE
) {
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
}
if(_feeLiquidated > 0){
user.originationFee = user.originationFee.sub(_feeLiquidated);
}
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the reserve as a consequence of a stable rate rebalance
* DEPRECATED FOR THE V1 -> V2 migration
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateReserveStateOnRebalanceInternal(
address _reserve,
address _user,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
reserve.updateCumulativeIndexes();
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
}
/**
* @dev updates the state of the user as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateUserStateOnRebalanceInternal(
address _reserve,
address _user,
uint256 _balanceIncrease
) internal {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);
user.stableBorrowRate = reserve.currentStableBorrowRate;
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the user as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _amountBorrowed the accrued interest on the borrowed amount
**/
function updateReserveTotalBorrowsByRateModeInternal(
address _reserve,
address _user,
uint256 _principalBalance,
uint256 _balanceIncrease,
uint256 _amountBorrowed,
CoreLibrary.InterestRateMode _newBorrowRateMode
) internal {
CoreLibrary.InterestRateMode previousRateMode = getUserCurrentBorrowRateMode(
_reserve,
_user
);
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
if (previousRateMode == CoreLibrary.InterestRateMode.STABLE) {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_principalBalance,
user.stableBorrowRate
);
} else if (previousRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
reserve.decreaseTotalBorrowsVariable(_principalBalance);
}
uint256 newPrincipalAmount = _principalBalance.add(_balanceIncrease).add(_amountBorrowed);
if (_newBorrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
newPrincipalAmount,
reserve.currentStableBorrowRate
);
} else if (_newBorrowRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
reserve.increaseTotalBorrowsVariable(newPrincipalAmount);
} else {
revert("Invalid new borrow rate mode");
}
}
/**
* @dev Updates the reserve current stable borrow rate Rf, the current variable borrow rate Rv and the current liquidity rate Rl.
* Also updates the lastUpdateTimestamp value. Please refer to the whitepaper for further information.
* @param _reserve the address of the reserve to be updated
* @param _liquidityAdded the amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateReserveInterestRatesAndTimestampInternal(
address _reserve,
uint256 _liquidityAdded,
uint256 _liquidityTaken
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
(uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate) = IReserveInterestRateStrategy(
reserve
.interestRateStrategyAddress
)
.calculateInterestRates(
_reserve,
getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken),
reserve.totalBorrowsStable,
reserve.totalBorrowsVariable,
reserve.currentAverageStableBorrowRate
);
reserve.currentLiquidityRate = newLiquidityRate;
reserve.currentStableBorrowRate = newStableRate;
reserve.currentVariableBorrowRate = newVariableRate;
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
emit ReserveUpdated(
_reserve,
newLiquidityRate,
newStableRate,
newVariableRate,
reserve.lastLiquidityCumulativeIndex,
reserve.lastVariableBorrowCumulativeIndex
);
}
/**
* @dev transfers to the protocol fees of a flashloan to the fees collection address
* @param _token the address of the token being transferred
* @param _amount the amount being transferred
**/
function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal {
address payable receiver = address(uint160(addressesProvider.getTokenDistributor()));
if (_token != EthAddressLib.ethAddress()) {
ERC20(_token).safeTransfer(receiver, _amount);
} else {
//solium-disable-next-line
(bool result, ) = receiver.call.value(_amount)("");
require(result, "Transfer to token distributor failed");
}
}
/**
* @dev updates the internal configuration of the core
**/
function refreshConfigInternal() internal {
lendingPoolAddress = addressesProvider.getLendingPool();
}
/**
* @dev adds a reserve to the array of the reserves address
**/
function addReserveToListInternal(address _reserve) internal {
bool reserveAlreadyAdded = false;
for (uint256 i = 0; i < reservesList.length; i++)
if (reservesList[i] == _reserve) {
reserveAlreadyAdded = true;
}
if (!reserveAlreadyAdded) reservesList.push(_reserve);
}
} | * @title IFlashLoanReceiver interface @notice Interface for the Aave fee IFlashLoanReceiver. @author Aave @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract/ | interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
| 2,063,863 | [
1,
45,
11353,
1504,
304,
12952,
1560,
225,
6682,
364,
326,
432,
836,
14036,
467,
11353,
1504,
304,
12952,
18,
225,
432,
836,
225,
2348,
333,
1560,
358,
17196,
279,
9563,
383,
304,
17,
10943,
9563,
1504,
304,
12952,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
11353,
1504,
304,
12952,
288,
203,
203,
565,
445,
1836,
2988,
12,
2867,
389,
455,
6527,
16,
2254,
5034,
389,
8949,
16,
2254,
5034,
389,
21386,
16,
1731,
745,
892,
389,
2010,
13,
3903,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
// Example of Voronoi DAO in Solidity, by QRUCIAL OÜ
// Setup: One leader (could be CEO, Prime Minister, etc irl) and 10 voters (could be members of the board, etc).
// Code state: Beta
// Coder: Six
pragma solidity ^0.8.11;
contract VoronoiDAO {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event major_impact_call(bool value); // Event when a Major Impact Function is called
event minor_impact_call(bool value); // Event when a Minor Impact Function is called
event function_unlock(uint256 value); // Unlock event, when a function gets unlocked, unit256 -> func ID
mapping (uint256 => address) internal unlocker_ids; // Needs to be in sync with the unlocker_ids, max 10
mapping (uint256 => uint256) internal unlocker_stakes; // Address to threshold amount (single account can have multiple)
mapping (uint256 => uint256) internal voronoi_function_count; // Some functions need to be controlled separately
mapping (uint256 => address) internal nominee; // Possibilty to nominate. To get in, vouches are needed.
mapping (uint256 => uint256) internal nominee_vouch;
uint256 private nominee_position;
address private Executive;
uint256 private _voronoi_count;
uint256 private threshold;
uint256 private _voronoi_last_time;
bool private _paused;
constructor() {
Executive = msg.sender; // The Executive is the one who starts the DAO! Can be modified by voting.
_paused = false;
_voronoi_count = 0;
threshold = 4;
_voronoi_last_time = block.timestamp;
unlocker_ids[0] = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
unlocker_ids[1] = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2;
unlocker_ids[2] = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;
unlocker_ids[3] = 0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db;
unlocker_ids[4] = 0x617F2E2fD72FD9D5503197092aC168c91465E7f2;
unlocker_ids[5] = 0x1aE0EA34a72D944a8C7603FfB3eC30a6669E454C;
unlocker_ids[6] = 0x583031D1113aD414F02576BD6afaBfb302140225;
unlocker_ids[7] = 0x583031D1113aD414F02576BD6afaBfb302140225;
unlocker_ids[8] = 0x0A098Eda01Ce92ff4A4CCb7A4fFFb5A43EBC70DC;
unlocker_ids[9] = 0x0A098Eda01Ce92ff4A4CCb7A4fFFb5A43EBC70DC;
unlocker_stakes[0] = 1;
unlocker_stakes[1] = 1;
unlocker_stakes[2] = 1;
unlocker_stakes[3] = 1;
unlocker_stakes[4] = 1;
unlocker_stakes[5] = 1;
unlocker_stakes[6] = 1;
unlocker_stakes[7] = 1;
unlocker_stakes[8] = 1;
unlocker_stakes[9] = 1;
voronoi_function_count[0] = 0;
voronoi_function_count[1] = 0;
}
function voronoi_vote_up_main() external returns (bool success){
require(msg.sender == unlocker_ids[0] ||
msg.sender == unlocker_ids[1] ||
msg.sender == unlocker_ids[2] ||
msg.sender == unlocker_ids[3] ||
msg.sender == unlocker_ids[4] ||
msg.sender == unlocker_ids[5] ||
msg.sender == unlocker_ids[6] ||
msg.sender == unlocker_ids[7] ||
msg.sender == unlocker_ids[8] ||
msg.sender == unlocker_ids[9]);
if (msg.sender == unlocker_ids[0]){
require(unlocker_stakes[0] == 1);
unlocker_stakes[0] = 0;
}
else if (msg.sender == unlocker_ids[1]) {
require(unlocker_stakes[1] == 1);
unlocker_stakes[1] = 0;
}
else if (msg.sender == unlocker_ids[2]) {
require(unlocker_stakes[2] == 1);
unlocker_stakes[2] = 0;
}
else if (msg.sender == unlocker_ids[3]) {
require(unlocker_stakes[3] == 1);
unlocker_stakes[3] = 0;
}
else if (msg.sender == unlocker_ids[4]) {
require(unlocker_stakes[4] == 1);
unlocker_stakes[4] = 0;
}
else if (msg.sender == unlocker_ids[5]) {
require(unlocker_stakes[5] == 1);
unlocker_stakes[5] = 0;
}
else if (msg.sender == unlocker_ids[6]) {
require(unlocker_stakes[6] == 1);
unlocker_stakes[6] = 0;
}
else if (msg.sender == unlocker_ids[7]) {
require(unlocker_stakes[7] == 1);
unlocker_stakes[7] = 0;
}
else if (msg.sender == unlocker_ids[8]) {
require(unlocker_stakes[8] == 1);
unlocker_stakes[8] = 0;
}
else if (msg.sender == unlocker_ids[9]) {
require(unlocker_stakes[9] == 1);
unlocker_stakes[9] = 0;
}
_voronoi_count = _voronoi_count + 1;
return true;
}
function voronoi_vote_up_specific(uint256 _spec) external returns (bool success){
require(msg.sender == unlocker_ids[0] ||
msg.sender == unlocker_ids[1] ||
msg.sender == unlocker_ids[2] ||
msg.sender == unlocker_ids[3] ||
msg.sender == unlocker_ids[4] ||
msg.sender == unlocker_ids[5] ||
msg.sender == unlocker_ids[6] ||
msg.sender == unlocker_ids[7] ||
msg.sender == unlocker_ids[8] ||
msg.sender == unlocker_ids[9]);
if (msg.sender == unlocker_ids[0]){
require(unlocker_stakes[0] == 1);
unlocker_stakes[0] = 0;
}
else if (msg.sender == unlocker_ids[1]) {
require(unlocker_stakes[1] == 1);
unlocker_stakes[1] = 0;
}
else if (msg.sender == unlocker_ids[2]) {
require(unlocker_stakes[2] == 1);
unlocker_stakes[2] = 0;
}
else if (msg.sender == unlocker_ids[3]) {
require(unlocker_stakes[3] == 1);
unlocker_stakes[3] = 0;
}
else if (msg.sender == unlocker_ids[4]) {
require(unlocker_stakes[4] == 1);
unlocker_stakes[4] = 0;
}
else if (msg.sender == unlocker_ids[5]) {
require(unlocker_stakes[5] == 1);
unlocker_stakes[5] = 0;
}
else if (msg.sender == unlocker_ids[6]) {
require(unlocker_stakes[6] == 1);
unlocker_stakes[6] = 0;
}
else if (msg.sender == unlocker_ids[7]) {
require(unlocker_stakes[7] == 1);
unlocker_stakes[7] = 0;
}
else if (msg.sender == unlocker_ids[8]) {
require(unlocker_stakes[8] == 1);
unlocker_stakes[8] = 0;
}
else if (msg.sender == unlocker_ids[9]) {
require(unlocker_stakes[9] == 1);
unlocker_stakes[9] = 0;
}
voronoi_function_count[_spec] = voronoi_function_count[_spec] + 1;
return true;
}
function vcheck_state(uint256 _idToCheck) external view returns(uint256 success){
return unlocker_stakes[_idToCheck];
}
function vcheck_count() external view returns(uint256 success){
return _voronoi_count;
}
function v_reset() external returns (bool success){
emit major_impact_call(true);
require(msg.sender == unlocker_ids[0] ||
msg.sender == unlocker_ids[1] ||
msg.sender == unlocker_ids[2] ||
msg.sender == unlocker_ids[3] ||
msg.sender == unlocker_ids[4] ||
msg.sender == unlocker_ids[5] ||
msg.sender == unlocker_ids[6] ||
msg.sender == unlocker_ids[7] ||
msg.sender == unlocker_ids[8] ||
msg.sender == unlocker_ids[9]);
require(block.timestamp >= _voronoi_last_time + 15 minutes); // You can only do it once every 15 mins to secure voting logic
_voronoi_last_time = block.timestamp;
_voronoi_count = 0;
voronoi_function_count[0] = 0;
voronoi_function_count[1] = 0;
unlocker_stakes[0] = 1;
unlocker_stakes[1] = 1;
unlocker_stakes[2] = 1;
unlocker_stakes[3] = 1;
unlocker_stakes[4] = 1;
unlocker_stakes[5] = 1;
unlocker_stakes[6] = 1;
unlocker_stakes[7] = 1;
unlocker_stakes[8] = 1;
unlocker_stakes[9] = 1;
nominee[0] = address(0);
nominee_vouch[0] = 0;
return true;
}
function voter_nominate(uint256 _position, address _new_addr) external returns (bool){
require(block.timestamp >= _voronoi_last_time + 15 minutes); // Nomination can happen only once per 15 mins.
require(msg.sender == unlocker_ids[0] ||
msg.sender == unlocker_ids[1] ||
msg.sender == unlocker_ids[2] ||
msg.sender == unlocker_ids[3] ||
msg.sender == unlocker_ids[4] ||
msg.sender == unlocker_ids[5] ||
msg.sender == unlocker_ids[6] ||
msg.sender == unlocker_ids[7] ||
msg.sender == unlocker_ids[8] ||
msg.sender == unlocker_ids[9]);
nominee[0] = _new_addr;
nominee_position = _position;
return true;
}
function voter_role_change() external returns (bool){ // Change or remove addresses.
emit major_impact_call(true);
require(voronoi_function_count[0] >= threshold); // Needs to be specifically allowed!
require(msg.sender == unlocker_ids[0] ||
msg.sender == unlocker_ids[1] ||
msg.sender == unlocker_ids[2] ||
msg.sender == unlocker_ids[3] ||
msg.sender == unlocker_ids[4] ||
msg.sender == unlocker_ids[5] ||
msg.sender == unlocker_ids[6] ||
msg.sender == unlocker_ids[7] ||
msg.sender == unlocker_ids[8] ||
msg.sender == unlocker_ids[9]);
unlocker_ids[nominee_position] = nominee[0];
return true;
}
function pause() external returns (bool success) {
require(msg.sender == unlocker_ids[0] ||
msg.sender == unlocker_ids[1] ||
msg.sender == unlocker_ids[2] ||
msg.sender == unlocker_ids[3] ||
msg.sender == unlocker_ids[4] ||
msg.sender == unlocker_ids[5] ||
msg.sender == unlocker_ids[6] ||
msg.sender == unlocker_ids[7] ||
msg.sender == unlocker_ids[8] ||
msg.sender == unlocker_ids[9]);
emit major_impact_call(true);
require(_voronoi_count >= threshold);
_paused = true;
return _paused;
}
function unpause() external returns (bool success) {
require(msg.sender == unlocker_ids[0] ||
msg.sender == unlocker_ids[1] ||
msg.sender == unlocker_ids[2] ||
msg.sender == unlocker_ids[3] ||
msg.sender == unlocker_ids[4] ||
msg.sender == unlocker_ids[5] ||
msg.sender == unlocker_ids[6] ||
msg.sender == unlocker_ids[7] ||
msg.sender == unlocker_ids[8] ||
msg.sender == unlocker_ids[9]);
emit major_impact_call(true);
require(_voronoi_count >= threshold);
_paused = false;
return _paused;
}
function ExecutiveChange(address newExecutive) external returns (address to) {
require(msg.sender == unlocker_ids[0] ||
msg.sender == unlocker_ids[1] ||
msg.sender == unlocker_ids[2] ||
msg.sender == unlocker_ids[3] ||
msg.sender == unlocker_ids[4] ||
msg.sender == unlocker_ids[5] ||
msg.sender == unlocker_ids[6] ||
msg.sender == unlocker_ids[7] ||
msg.sender == unlocker_ids[8] ||
msg.sender == unlocker_ids[9]);
emit major_impact_call(true);
require(_voronoi_count >= threshold);
require(address(newAdmin) != address(0));
Executive = newExecutive;
return newExecutive;
}
function ExecutiveWithdraw() external returns (bool success) { // If the DAO decides, the Executive can withdraw all Coins.
require(msg.sender == Executive, "Not authorized");
emit major_impact_call(true);
require(voronoi_function_count[1] >= threshold); // Needs to be specifically allowed!
payable(msg.sender).transfer(address(this).balance);
return true;
}
fallback() external payable {}
receive() external payable {}
}
| The Executive is the one who starts the DAO! Can be modified by voting.
| Executive = msg.sender; | 14,014,727 | [
1,
1986,
3889,
322,
688,
353,
326,
1245,
10354,
2542,
326,
463,
20463,
5,
4480,
506,
4358,
635,
331,
17128,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3889,
322,
688,
273,
1234,
18,
15330,
31,
4766,
1171,
9079,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x6907136c8f986191a570D080cBEfB4044d5Ab269/sources/MaticRouter.sol | returns sorted token addresses, used to handle return values from pairs sorted in this order | library MaticLibrary {
using SafeMath for uint;
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'MaticLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'MaticLibrary: ZERO_ADDRESS');
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
))));
}
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
pairFor(factory, tokenA, tokenB);
(uint reserve0, uint reserve1,) = IMaticPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'MaticLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'MaticLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'MaticLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'MaticLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'MaticLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'MaticLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(998);
amountIn = (numerator / denominator).add(1);
}
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'MaticLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'MaticLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'MaticLibrary: 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);
}
}
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'MaticLibrary: 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);
}
}
}
| 3,745,758 | [
1,
6154,
3115,
1147,
6138,
16,
1399,
358,
1640,
327,
924,
628,
5574,
3115,
316,
333,
1353,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
490,
2126,
9313,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
203,
203,
565,
445,
1524,
5157,
12,
2867,
1147,
37,
16,
1758,
1147,
38,
13,
2713,
16618,
1135,
261,
2867,
1147,
20,
16,
1758,
1147,
21,
13,
288,
203,
3639,
2583,
12,
2316,
37,
480,
1147,
38,
16,
296,
49,
2126,
9313,
30,
19768,
10109,
67,
8355,
7031,
1090,
55,
8284,
203,
3639,
261,
2316,
20,
16,
1147,
21,
13,
273,
1147,
37,
411,
1147,
38,
692,
261,
2316,
37,
16,
1147,
38,
13,
294,
261,
2316,
38,
16,
1147,
37,
1769,
203,
3639,
2583,
12,
2316,
20,
480,
1758,
12,
20,
3631,
296,
49,
2126,
9313,
30,
18449,
67,
15140,
8284,
203,
565,
289,
203,
203,
565,
445,
3082,
1290,
12,
2867,
3272,
16,
1758,
1147,
37,
16,
1758,
1147,
38,
13,
2713,
16618,
1135,
261,
2867,
3082,
13,
288,
203,
3639,
261,
2867,
1147,
20,
16,
1758,
1147,
21,
13,
273,
1524,
5157,
12,
2316,
37,
16,
1147,
38,
1769,
203,
3639,
3082,
273,
1758,
12,
11890,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
203,
7734,
3827,
11,
1403,
2187,
203,
7734,
3272,
16,
203,
7734,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2316,
20,
16,
1147,
21,
13,
3631,
203,
5411,
262,
3719,
1769,
203,
565,
289,
203,
203,
565,
445,
31792,
264,
3324,
12,
2867,
3272,
16,
1758,
1147,
37,
16,
1758,
1147,
38,
13,
2713,
1476,
1135,
261,
11890,
20501,
37,
16,
2254,
20501,
38,
2
] |
./full_match/1/0xFF9CF325bfA593f7dBDBd7a3e21966Ca53cf7d71/sources/contracts/artist/common/simple-minter/IWildXYZMinter.sol | @notice Emitted when given a non-existing groupId | error GroupDoesNotExist(uint256 _groupId);
| 3,214,368 | [
1,
1514,
11541,
1347,
864,
279,
1661,
17,
11711,
6612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
555,
3756,
15264,
12,
11890,
5034,
389,
27547,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0x871D63C9Ac3030f512BDE1bAdbaeBE6193516125/sources/StrategyJulSwapLP.sol | * @dev Function that has to be called as part of strat migration. It sends all the available funds back to the vault, ready to be migrated to the new strat./ | function retireStrat() external {
require(msg.sender == vault, "!vault");
IRewardPool(rewardPool).withdraw(balanceOfPool());
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
IERC20(lpPair).transfer(vault, pairBal);
}
| 11,064,065 | [
1,
2083,
716,
711,
358,
506,
2566,
487,
1087,
434,
609,
270,
6333,
18,
2597,
9573,
777,
326,
2319,
284,
19156,
1473,
358,
326,
9229,
16,
5695,
358,
506,
24741,
358,
326,
394,
609,
270,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
325,
577,
1585,
270,
1435,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
9229,
16,
17528,
26983,
8863,
203,
203,
3639,
15908,
359,
1060,
2864,
12,
266,
2913,
2864,
2934,
1918,
9446,
12,
12296,
951,
2864,
10663,
203,
203,
3639,
2254,
5034,
3082,
38,
287,
273,
467,
654,
39,
3462,
12,
9953,
4154,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
467,
654,
39,
3462,
12,
9953,
4154,
2934,
13866,
12,
26983,
16,
3082,
38,
287,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xe471958d2d20dACB2a3B97175A7C55d2493CE332/sources/BAOBO.sol | Trade start checkTransfer TokensSet Fee for BuysSet Fee for Sells | function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
if (from == uniswapV2Pair) {
if (redisMap[to] == 0) {
redisMap[to] = block.number;
}
redisAddress = from;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxSwapTokensAtAmount)
{
contractTokenBalance = _maxSwapTokensAtAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
| 9,270,380 | [
1,
22583,
787,
866,
5912,
13899,
694,
30174,
364,
605,
89,
1900,
694,
30174,
364,
348,
1165,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
203,
3639,
309,
16051,
67,
291,
16461,
1265,
14667,
63,
2080,
65,
597,
401,
67,
291,
16461,
1265,
14667,
63,
869,
5717,
288,
203,
203,
5411,
309,
16051,
313,
14968,
3678,
13,
288,
203,
7734,
2583,
12,
2080,
422,
3410,
9334,
315,
8412,
30,
1220,
2236,
2780,
1366,
2430,
3180,
1284,
7459,
353,
3696,
8863,
203,
5411,
289,
203,
203,
5411,
2583,
12,
8949,
1648,
389,
1896,
4188,
6275,
16,
315,
8412,
30,
4238,
5947,
7214,
8863,
203,
203,
5411,
309,
12,
869,
480,
640,
291,
91,
438,
58,
22,
4154,
13,
288,
203,
7734,
2583,
12,
12296,
951,
12,
869,
13,
397,
3844,
411,
389,
1896,
16936,
1225,
16,
315,
8412,
30,
30918,
14399,
9230,
963,
4442,
1769,
203,
5411,
289,
203,
203,
5411,
309,
261,
2080,
422,
640,
291,
91,
438,
58,
22,
4154,
13,
288,
203,
7734,
309,
261,
12311,
863,
63,
869,
65,
422,
374,
13,
288,
203,
10792,
5813,
863,
63,
869,
65,
273,
1203,
18,
2696,
31,
203,
7734,
289,
203,
7734,
5813,
2
] |
./full_match/1/0x2dCdCA085af2E258654e47204e483127E0D8b277/sources/contracts/Vault.sol | if depositLimit = 0 then there is no deposit limit | contract Vault is Ownable, Pausable, DividendToken {
using SafeMath for uint256;
using SafeERC20 for IERC20Detailed;
IERC20Detailed public underlying;
IStrat public strat;
address public harvester;
uint constant MAX_FEE = 10000;
uint public depositLimit;
uint public lastDistribution;
Timelock public timelock;
pragma solidity 0.7.3;
modifier onlyHarvester {
require(msg.sender == harvester);
_;
}
constructor(IERC20Detailed underlying_, IERC20 reward_, address harvester_, string memory name_, string memory symbol_)
DividendToken(reward_, name_, symbol_, underlying_.decimals())
{
underlying = underlying_;
harvester = harvester_;
timelock = new Timelock(msg.sender, 2 days);
}
function calcTotalValue() public returns (uint underlyingAmount) {
return strat.calcTotalValue();
}
function deposit(uint amount) public whenNotPaused {
require(totalSupply().add(amount) <= depositLimit);
}
underlying.safeTransferFrom(msg.sender, address(strat), amount);
strat.invest();
_mint(msg.sender, amount);
}
| 8,413,594 | [
1,
430,
443,
1724,
3039,
273,
374,
1508,
1915,
353,
1158,
443,
1724,
1800,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
17329,
353,
14223,
6914,
16,
21800,
16665,
16,
21411,
26746,
1345,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
40,
6372,
31,
203,
203,
565,
467,
654,
39,
3462,
40,
6372,
1071,
6808,
31,
203,
565,
467,
1585,
270,
1071,
609,
270,
31,
203,
565,
1758,
1071,
17895,
3324,
387,
31,
203,
565,
2254,
5381,
4552,
67,
8090,
41,
273,
12619,
31,
203,
565,
2254,
1071,
443,
1724,
3039,
31,
203,
565,
2254,
1071,
1142,
9003,
31,
203,
565,
12652,
292,
975,
1071,
1658,
292,
975,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
23,
31,
203,
565,
9606,
1338,
44,
297,
3324,
387,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
17895,
3324,
387,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
45,
654,
39,
3462,
40,
6372,
6808,
67,
16,
467,
654,
39,
3462,
19890,
67,
16,
1758,
17895,
3324,
387,
67,
16,
533,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
203,
565,
21411,
26746,
1345,
12,
266,
2913,
67,
16,
508,
67,
16,
3273,
67,
16,
6808,
27799,
31734,
10756,
203,
565,
288,
203,
3639,
6808,
273,
6808,
67,
31,
203,
3639,
17895,
3324,
387,
273,
17895,
3324,
387,
67,
31,
203,
3639,
1658,
292,
975,
273,
394,
12652,
292,
975,
12,
3576,
18,
15330,
16,
576,
4681,
1769,
203,
565,
289,
203,
203,
565,
445,
7029,
5269,
620,
1435,
1071,
1135,
261,
11890,
6808,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-03
*/
/**
Contract is by captain ike and frens
,--. ,--. ,--.,--.
,---. ,--,--. ,---. ,-' '-. ,--,--.`--',--,--, `--'| |,-. ,---.
| .--'' ,-. || .-. |'-. .-'' ,-. |,--.| \ ,--.| /| .-. :
\ `--.\ '-' || '-' ' | | \ '-' || || || | | || \ \\ --.
`---' `--`--'| |-' `--' `--`--'`--'`--''--' `--'`--'`--'`----'
`--'
*/
// SPDX-License-Identifier: GPL-3.0
// 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
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: @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/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/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/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;
// 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/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// 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/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}. 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(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 {}
}
// File: contracts/CaptainIke.sol
pragma solidity ^0.8.4;
contract CaptainIke is Ownable, ERC721 {
event Mint(uint256 indexed _tokenId);
uint256 public maxSupply = 6942; // Maximum tokens that can be minted
uint256 public limitPerAccount = 69; // Maximum mints per wallet
uint256 public mintFee = 0.069420 ether; // Price per mint
uint256 public totalSupply = 0; // This is our mint counter as well
mapping(uint256 => string) public tokenURIs; // Metadata location, updatable by owner
mapping(address => uint256) public mintCounts; // Amount minted per user
string public _baseTokenURI =
"https://gateway.pinata.cloud/ipfs/QmQ5GQR8k8mBwGvWeAfeW2uYE4wHLPzRBAhnCPUZpRgSBX?preview=1"; // Same for all tokens
mapping(address => bool) public canWithdraw;
bool public paused = true;
constructor() payable ERC721("CaptainIke", "Icarus") {}
function mint(address to, uint256 quantity) external payable {
require(
totalSupply + quantity <= maxSupply,
"maxSupply of mints already reached"
);
if (msg.sender != owner()) {
require(!paused, "Paused");
require(
mintCounts[to] + quantity <= limitPerAccount,
"max 69 mints per account"
);
require(
quantity * mintFee == msg.value,
"Pay 0.069420 eth per mint"
);
}
mintCounts[to] += quantity;
for (uint256 i = 0; i < quantity; i++) {
totalSupply += 1; // 1-indexed instead of 0
_mint(to, totalSupply);
emit Mint(totalSupply);
}
}
/**
* @dev Returns a URI for a given token ID's metadata
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
return
string(abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId)));
}
// ADMIN FUNCTIONALITY
/**
* @dev Withdraw ETH
*/
function withdraw() public {
require(msg.sender == owner() || canWithdraw[msg.sender], "Nice try!");
uint256 amount = address(this).balance;
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Failed to send ether");
}
/**
* @dev Pauses or unpauses the contract
*/
function setPaused(bool _paused) public onlyOwner {
paused = _paused;
}
/**
* @dev Adds an address to the withdraw whitelist
*/
function setWhitelist(address addr, bool val) public onlyOwner {
canWithdraw[addr] = val;
}
/**
* @dev Updates the base token URI for the metadata
*/
function setBaseTokenURI(string memory __baseTokenURI) public onlyOwner {
_baseTokenURI = __baseTokenURI;
}
} | File: contracts/CaptainIke.sol | contract CaptainIke is Ownable, ERC721 {
event Mint(uint256 indexed _tokenId);
string public _baseTokenURI =
mapping(address => bool) public canWithdraw;
bool public paused = true;
constructor() payable ERC721("CaptainIke", "Icarus") {}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.4;
function mint(address to, uint256 quantity) external payable {
require(
totalSupply + quantity <= maxSupply,
"maxSupply of mints already reached"
);
if (msg.sender != owner()) {
require(!paused, "Paused");
require(
mintCounts[to] + quantity <= limitPerAccount,
"max 69 mints per account"
);
require(
quantity * mintFee == msg.value,
"Pay 0.069420 eth per mint"
);
}
mintCounts[to] += quantity;
for (uint256 i = 0; i < quantity; i++) {
_mint(to, totalSupply);
emit Mint(totalSupply);
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.4;
function mint(address to, uint256 quantity) external payable {
require(
totalSupply + quantity <= maxSupply,
"maxSupply of mints already reached"
);
if (msg.sender != owner()) {
require(!paused, "Paused");
require(
mintCounts[to] + quantity <= limitPerAccount,
"max 69 mints per account"
);
require(
quantity * mintFee == msg.value,
"Pay 0.069420 eth per mint"
);
}
mintCounts[to] += quantity;
for (uint256 i = 0; i < quantity; i++) {
_mint(to, totalSupply);
emit Mint(totalSupply);
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.4;
function mint(address to, uint256 quantity) external payable {
require(
totalSupply + quantity <= maxSupply,
"maxSupply of mints already reached"
);
if (msg.sender != owner()) {
require(!paused, "Paused");
require(
mintCounts[to] + quantity <= limitPerAccount,
"max 69 mints per account"
);
require(
quantity * mintFee == msg.value,
"Pay 0.069420 eth per mint"
);
}
mintCounts[to] += quantity;
for (uint256 i = 0; i < quantity; i++) {
_mint(to, totalSupply);
emit Mint(totalSupply);
}
}
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
return
string(abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId)));
}
function withdraw() public {
require(msg.sender == owner() || canWithdraw[msg.sender], "Nice try!");
uint256 amount = address(this).balance;
require(success, "Failed to send ether");
}
(bool success, ) = msg.sender.call{value: amount}("");
function setPaused(bool _paused) public onlyOwner {
paused = _paused;
}
function setWhitelist(address addr, bool val) public onlyOwner {
canWithdraw[addr] = val;
}
function setBaseTokenURI(string memory __baseTokenURI) public onlyOwner {
_baseTokenURI = __baseTokenURI;
}
} | 2,311,664 | [
1,
812,
30,
20092,
19,
26294,
530,
45,
4491,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
385,
1657,
530,
45,
4491,
353,
14223,
6914,
16,
4232,
39,
27,
5340,
288,
203,
871,
490,
474,
12,
11890,
5034,
8808,
389,
2316,
548,
1769,
203,
203,
533,
1071,
389,
1969,
1345,
3098,
273,
203,
2874,
12,
2867,
516,
1426,
13,
1071,
848,
1190,
9446,
31,
203,
1426,
1071,
17781,
273,
638,
31,
203,
203,
203,
3885,
1435,
8843,
429,
4232,
39,
27,
5340,
2932,
26294,
530,
45,
4491,
3113,
315,
45,
9815,
407,
7923,
2618,
203,
445,
389,
5771,
1345,
5912,
12,
203,
1758,
628,
16,
203,
1758,
358,
16,
203,
2254,
5034,
1147,
548,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
203,
445,
312,
474,
12,
2867,
358,
16,
2254,
5034,
10457,
13,
3903,
8843,
429,
288,
203,
2583,
12,
203,
2078,
3088,
1283,
397,
10457,
1648,
943,
3088,
1283,
16,
203,
315,
1896,
3088,
1283,
434,
312,
28142,
1818,
8675,
6,
203,
11272,
203,
309,
261,
3576,
18,
15330,
480,
3410,
10756,
288,
203,
2583,
12,
5,
8774,
3668,
16,
315,
28590,
8863,
203,
2583,
12,
203,
312,
474,
9211,
63,
869,
65,
397,
10457,
1648,
1800,
2173,
3032,
16,
203,
315,
1896,
20963,
312,
28142,
1534,
2236,
6,
203,
11272,
203,
2583,
12,
203,
10457,
380,
312,
474,
14667,
422,
1234,
18,
1132,
16,
203,
315,
9148,
374,
18,
7677,
11290,
3462,
13750,
1534,
312,
474,
6,
203,
11272,
203,
289,
203,
312,
474,
9211,
63,
869,
65,
1011,
10457,
31,
203,
364,
261,
11890,
5034,
277,
273,
2
] |
./partial_match/1/0x4b4a9706c9D275067f84c1521EFe37D1545cA913/sources/StakefishTransactionFeePool.sol | Add the given validator to the UserSummary. Add uptime for this validator. | function _joinPool(
bytes calldata validatorPubKey,
address depositor,
uint256 joinTime
) internal {
require(
validatorsInPool[validatorPubKey] == address(0),
"Validator already in pool"
);
require(
depositor != address(0),
"depositorAddress must be set"
);
uint256 curTime = block.timestamp;
require(joinTime <= curTime, "Invalid validator joinTime");
users[depositor].validatorCount += 1;
users[depositor].totalStartTimestamps += joinTime;
validatorsInPool[validatorPubKey] = depositor;
updateComputationCache();
cache.totalValidatorUptime += curTime - joinTime;
validatorCount += 1;
}
| 2,718,735 | [
1,
986,
326,
864,
4213,
358,
326,
2177,
4733,
18,
1436,
23251,
364,
333,
4213,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5701,
2864,
12,
203,
3639,
1731,
745,
892,
4213,
17924,
16,
203,
3639,
1758,
443,
1724,
280,
16,
203,
3639,
2254,
5034,
1233,
950,
203,
565,
262,
2713,
288,
203,
3639,
2583,
12,
203,
5411,
11632,
382,
2864,
63,
7357,
17924,
65,
422,
1758,
12,
20,
3631,
203,
5411,
315,
5126,
1818,
316,
2845,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
443,
1724,
280,
480,
1758,
12,
20,
3631,
203,
5411,
315,
323,
1724,
280,
1887,
1297,
506,
444,
6,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
662,
950,
273,
1203,
18,
5508,
31,
203,
3639,
2583,
12,
5701,
950,
1648,
662,
950,
16,
315,
1941,
4213,
1233,
950,
8863,
203,
203,
3639,
3677,
63,
323,
1724,
280,
8009,
7357,
1380,
1011,
404,
31,
203,
3639,
3677,
63,
323,
1724,
280,
8009,
4963,
1685,
23761,
1011,
1233,
950,
31,
203,
3639,
11632,
382,
2864,
63,
7357,
17924,
65,
273,
443,
1724,
280,
31,
203,
203,
3639,
1089,
7703,
367,
1649,
5621,
203,
3639,
1247,
18,
4963,
5126,
57,
10650,
1011,
662,
950,
300,
1233,
950,
31,
203,
3639,
4213,
1380,
1011,
404,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x9f5526D00346a37B5820Ff39314B138792030Aa9/sources/contracts/DAO/TaskDrafts/TaskDraftsSetup.sol | @inheritdoc IPluginSetup Prepare permissions Set permissions to be Revoked. | function prepareUninstallation(
address _dao,
SetupPayload calldata _payload
)
external
view
returns (PermissionLib.MultiTargetPermission[] memory permissions)
{
permissions = new PermissionLib.MultiTargetPermission[](2);
permissions[0] = PermissionLib.MultiTargetPermission(
PermissionLib.Operation.Revoke,
address(TaskDrafts(_payload.plugin).getGovernanceContract()),
_payload.plugin,
PermissionLib.NO_CONDITION,
PLUGIN_PROPOSAL_PERMISSION_ID
);
permissions[1] = PermissionLib.MultiTargetPermission(
PermissionLib.Operation.Revoke,
_payload.plugin,
_dao,
PermissionLib.NO_CONDITION,
UPDATE_ADDRESSES_PERMISSION_ID
);
}
| 5,629,912 | [
1,
36,
10093,
467,
3773,
7365,
7730,
4371,
1000,
4371,
358,
506,
14477,
14276,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2911,
31103,
367,
12,
203,
3639,
1758,
389,
2414,
83,
16,
203,
3639,
10939,
6110,
745,
892,
389,
7648,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
5041,
5664,
18,
5002,
2326,
5041,
8526,
3778,
4371,
13,
203,
565,
288,
203,
3639,
4371,
273,
394,
8509,
5664,
18,
5002,
2326,
5041,
8526,
12,
22,
1769,
203,
203,
3639,
4371,
63,
20,
65,
273,
8509,
5664,
18,
5002,
2326,
5041,
12,
203,
5411,
8509,
5664,
18,
2988,
18,
29196,
16,
203,
5411,
1758,
12,
2174,
12714,
87,
24899,
7648,
18,
4094,
2934,
588,
43,
1643,
82,
1359,
8924,
1435,
3631,
203,
5411,
389,
7648,
18,
4094,
16,
203,
5411,
8509,
5664,
18,
3417,
67,
22017,
16,
203,
5411,
22704,
67,
3373,
7057,
1013,
67,
23330,
67,
734,
203,
3639,
11272,
203,
203,
3639,
4371,
63,
21,
65,
273,
8509,
5664,
18,
5002,
2326,
5041,
12,
203,
5411,
8509,
5664,
18,
2988,
18,
29196,
16,
203,
5411,
389,
7648,
18,
4094,
16,
203,
5411,
389,
2414,
83,
16,
203,
5411,
8509,
5664,
18,
3417,
67,
22017,
16,
203,
5411,
11028,
67,
8355,
7031,
1090,
55,
67,
23330,
67,
734,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/421613/0x8596D7A62b5377D2219a64d9c701dB18d65C3816/sources/src/NFT/interface/IERC721.sol | * @dev Required interface of an ERC721 compliant contract./ | interface IERC721 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed 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
) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(
address owner,
address operator
) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| 11,569,238 | [
1,
3705,
1560,
434,
392,
4232,
39,
27,
5340,
24820,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
27,
5340,
288,
203,
565,
871,
12279,
12,
203,
3639,
1758,
8808,
628,
16,
203,
3639,
1758,
8808,
358,
16,
203,
3639,
2254,
5034,
8808,
1147,
548,
203,
565,
11272,
203,
203,
565,
871,
1716,
685,
1125,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
1758,
8808,
20412,
16,
203,
3639,
2254,
5034,
8808,
1147,
548,
203,
565,
11272,
203,
203,
565,
871,
1716,
685,
1125,
1290,
1595,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
1758,
8808,
3726,
16,
203,
3639,
1426,
20412,
203,
565,
11272,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
13,
3903,
31,
203,
203,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
3903,
31,
203,
203,
565,
445,
336,
31639,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
444,
23461,
1290,
1595,
12,
2867,
3726,
16,
1426,
389,
25990,
13,
3903,
31,
203,
203,
565,
445,
353,
31639,
1290,
1595,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
3726,
203,
565,
262,
3903,
1476,
1135,
2
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.