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 |
---|---|---|---|---|---|---|
pragma solidity ^0.8.3;
/*
* \title Hakutaku token
* \brief Token that every X hours rewards a randomly selected holder (that held for long enough)
* with the total amount accumulated in a pool from transaction fees
* \version 1.0b experimental
* \author unknown
*/
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
contract HTT is ERC20, Ownable {
address prize_pool; //!< prize draw pool address
uint prize_pool_fee; //!< percent fee on every transaction that goes towards prize pool (1-10% limit)
uint prize_frequency; //!< how often does the prize draw happen (1h - 1d limit)
uint hold_balance_limit; //!< amount to hold to be eligible for a prize draw (1-1M token limit)
uint hold_time_limit; //!< must hold at least this time (2-25 hr limit)
struct Holder {
address addr;
uint time; // timestamp when accumulated enough HTT
}
Holder[] holders; //!< holders (will become diamond hands once time passes)
struct Diamond {
address addr;
uint value; // value with which became a diamond hands holder
}
Diamond[] diamonds; //!< eligible holders for the reward (diamond hands)
mapping(address => uint) holder_indexes; //!< mapping of address to indexes in holders array
mapping(address => uint) diamond_indexes; //!< mapping of address to indexes in diamonds array
uint prize_last_time; //!< last time the prize draw happened
uint prize_last_amount; //!< last amount given to rewardee
uint totalam; //!< total amount of tokens diamond hands accumulated
bool buy_limit; //!< protection from whales (removed shortly after the launch)
constructor(
address _prize_pool,
uint _prize_pool_fee,
uint _prize_frequency,
uint _hold_balance_limit,
uint _hold_time_limit,
bool _buy_limit)
Ownable() ERC20('Hakutaku Token', 'HAKU') {
_mint(msg.sender, 1000000000 * 10 ** 18);
_addHolder(msg.sender); // fill index 0
_addDiamond(msg.sender, _hold_balance_limit); // fill index 0
totalam = 0; // init totalam
prize_pool = _prize_pool; // hardcoded prize pool (this account will not be able to trade tokens!)
setPrizePoolFee(_prize_pool_fee);
setHoldTimeLimit(_hold_time_limit);
setPrizeFrequency(_prize_frequency);
setHoldBalanceLimit(_hold_balance_limit);
prize_last_time = block.timestamp; // init prize timestamp
prize_last_amount = 0;
buy_limit = _buy_limit;
}
/*!
* \title Override transfer function
* \brief Takes prize fee from every transaction
* Initiates reward prize draw
*/
function _transfer(address from, address to, uint256 value) override internal {
// block prize pool from dumping tokens
require(from != prize_pool, "prize pool cannot trade tokens");
require(to != prize_pool, "prize pool cannot trade tokens");
// put fee into the prize pool
if(from != owner() && to != owner()) {
uint256 prize_fee = calcFee(value);
value -= prize_fee; // take fee out
if(buy_limit) {
require(value <= hold_balance_limit, "buy/sell limit");
require(balanceOf(to) + value <= hold_balance_limit, "hold limit");
}
super._transfer(from, prize_pool, prize_fee);
}
super._transfer(from, to, value);
// are there pending holders waiting to become diamond hands?
if(holders.length > 1) {
uint i = holders.length-1;
uint steps = 0;
// process max 10 at a time to save gas
while(steps < 10 && i > 0) {
if(holder_indexes[holders[i].addr] > 0 && diamond_indexes[holders[i].addr] == 0 && holders[i].time > 0 && (block.timestamp - holders[i].time) >= hold_time_limit) {
_addDiamond(holders[i].addr, balanceOf(holders[i].addr)); // add to diamond hands
_removeHolder(holders[i].addr); // delete from pending
}
steps++;
i--;
}
}
// do we need to trigger a reward?
if(block.timestamp > prize_last_time && (block.timestamp - prize_last_time) >= prize_frequency && balanceOf(prize_pool) > 0) {
prize_last_time = block.timestamp; // update last time a prize was given
// prize given only if there are diamond hands
if(diamonds.length > 1) {
// calc total amount for mid, 1/4 and 3/4 holder
uint indmid = uint(diamonds.length) / uint(2);
uint indlq = indmid / uint(2);
uint totalamex = diamonds[indmid].value + diamonds[indlq].value + diamonds[indlq+indmid].value;
// choose a rewardee from diamond hands holders
uint rewardee_ind = 1 + getHakutakuChoice(diamonds.length-1, totalamex); // if we get 0, it's 1
prize_last_amount = balanceOf(prize_pool);
// give everything from the prize pool to the rewardee
super._transfer(prize_pool, diamonds[rewardee_ind].addr, prize_last_amount);
}
}
// if accumulated enough and not in holders yet -- add
// note1: owner is a permanent holder (but will never take part in prize draws!)
// note2: prize_pool is not in holders and never will be
// note3: owner and prize pool do not get added or removed to these lists after constructor
uint bto = balanceOf(to);
uint bfrom = balanceOf(from);
if(bto >= hold_balance_limit && holder_indexes[to] == 0 && diamond_indexes[to] == 0 && to != owner() && to != prize_pool) {
_addHolder(to);
}
if(bfrom >= hold_balance_limit && holder_indexes[from] == 0 && diamond_indexes[from] == 0 && from != owner() && from != prize_pool) {
_addHolder(from);
}
// if below hold limit (he sold? d0mp him!)
if(bfrom < hold_balance_limit && from != owner() && from != prize_pool) {
if(holder_indexes[from] > 0) {
_removeHolder(from);
}
if(diamond_indexes[from] > 0) {
_removeDiamond(from);
}
}
if(bto < hold_balance_limit && to != owner() && to != prize_pool) {
if(holder_indexes[to] > 0) {
_removeHolder(to);
}
if(diamond_indexes[to] > 0) {
_removeDiamond(to);
}
}
}
/*!
* \title Hakutaku makes a choice of the rewardee
* \brief He decides based on what holders did. It is completely decentralised.
* Warning: the choice is pseudo-random, not strictly random, this code is experimental
* Note, however, that the hypothetical effort to turn this choice into personal benefit via an exploit
* is expected to be larger than the benefit because of the holding time limit, holding amount limit and
* randomness introduced by holder actions. Moreover, the frequency of the prize draw in comparison with
* the holding time limit and holding balance limit makes the cost of manipulation too high.
* With that being said, we don't make any claims, it is experimental, always do your own research.
* \return index of the rewardee
*/
function getHakutakuChoice(uint num, uint totalamex) internal view returns(uint) {
return uint(keccak256(abi.encodePacked(totalam, totalamex, prize_last_amount))) % num;
}
/*!
* \title Calculate prize fee for a transaction value
* \return fee in tokens
*/
function calcFee(uint256 value) public view returns (uint256) {
return (value / 100) * prize_pool_fee;
}
function _addHolder(address holder) internal {
holders.push(Holder(holder, block.timestamp));
holder_indexes[holder] = holders.length - 1;
}
function _removeHolder(address holder) internal {
uint ind = holder_indexes[holder];
if(ind < holders.length-1) {
holders[ind] = holders[holders.length-1]; // replace current index with last holder
holder_indexes[holders[ind].addr] = ind; // update last holder's index to new one
}
holders.pop(); // pop last item of the holders
delete holder_indexes[holder]; // clear the holder who sold
}
function _addDiamond(address diamond, uint value) internal {
diamonds.push(Diamond(diamond, value));
diamond_indexes[diamond] = diamonds.length - 1;
totalam += value;
}
function _removeDiamond(address diamond) internal {
uint ind = diamond_indexes[diamond];
totalam -= diamonds[ind].value; // his value is out of the totalam
if(ind < diamonds.length-1) {
diamonds[ind] = diamonds[diamonds.length-1]; // replace current index with last diamond
diamond_indexes[diamonds[ind].addr] = ind; // update last diamond's index to new one
}
diamonds.pop(); // pop last item of the holders
delete diamond_indexes[diamond]; // clear the diamond who sold
}
function getPrizeLastTime() external view returns (uint) {
return prize_last_time;
}
function getPrizePoolFee() external view returns (uint) {
return prize_pool_fee;
}
function getPrizeFrequency() external view returns (uint) {
return prize_frequency;
}
function getHoldBalanceLimit() external view returns (uint) {
return hold_balance_limit;
}
function getHoldTimeLimit() external view returns (uint) {
return hold_time_limit;
}
function getHoldersCount() external view returns(uint) {
return holders.length;
}
function getDiamondsCount() external view returns(uint) {
return diamonds.length;
}
function setPrizeFrequency(uint _prize_frequency) public onlyOwner {
require(_prize_frequency >= 1800 && _prize_frequency <= 86400, "frequency of the reward must be between 30m and 1d");
require(hold_time_limit >= 3600 + _prize_frequency, "houd hour limit must be at least 1 hour longer than reward frequency");
prize_frequency = _prize_frequency;
}
function setPrizePoolFee(uint _prize_pool_fee) public onlyOwner {
require(_prize_pool_fee >= 1 && _prize_pool_fee <= 10, "prize pool fee must be 1-10%");
prize_pool_fee = _prize_pool_fee;
}
function setHoldBalanceLimit(uint _hold_balance_limit) public onlyOwner {
require(_hold_balance_limit >= 1 * 10 ** 18 && _hold_balance_limit <= 10000000 * 10 ** 18, "balance limit must be between 1 and 10M");
hold_balance_limit = _hold_balance_limit;
}
function setHoldTimeLimit(uint _hold_time_limit) public onlyOwner {
require(_hold_time_limit >= 7200 && _hold_time_limit <= 90000, "hold time limit has to be between 2 and 25");
require(_hold_time_limit >= 3600 + prize_frequency, "hold time limit must be at least 1 hour longer than reward frequency");
hold_time_limit = _hold_time_limit;
}
function removeBuyLimit() external onlyOwner {
buy_limit = false; // can be done only once and can't be reverted!
}
} | update last time a prize was given
| prize_last_time = block.timestamp; | 6,342,815 | [
1,
2725,
1142,
813,
279,
846,
554,
1703,
864,
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,
1082,
202,
683,
554,
67,
2722,
67,
957,
273,
1203,
18,
5508,
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
] |
pragma solidity ^0.5.10;
/**
Get 20% profit every month with a contract Shareholder VOMER!
*
* - OBTAINING 20% PER 1 MONTH. (percentages are charged in equal parts every 1 sec.)
* 0,33 - for 1 day
* 0,013 - for 1 hour
* 0.00023 - for 1 minute
* 0.0000038 - for 1 sec
* - lifetime payments
* - unprecedentedly reliable
* - bring luck
* - minimum contribution of 0.01 fl
* - Currency and Payment - ETH
* - Contribution allocation schemes:
* - 100% of payments - 5% percent for support and 25% percent referral system.
*
* VOMER.net
*
* RECOMMENDED GAS LIMIT: 200,000
* RECOMMENDED GAS PRICE: https://ethgasstation.info/
* DO NOT TRANSFER DIRECTLY FROM AN EXCHANGE (only use your ETH wallet, from which you have a private key)
* You can check payments on the website etherscan.io, in the “Internal Txns” tab of your wallet.
*
* Referral system 25%.
* Payments to developers 5%
* Restart of the contract is also absent. If there is no money in the Fund, payments are stopped and resumed after the Fund is filled. Thus, the contract will work forever!
*
* How to use:
* 1. Send from your ETH wallet to the address of the smart contract
* Any amount from 2.00 ETH.
* 2. Confirm your transaction in the history of your application or etherscan.io, indicating the address of your wallet.
* Take profit by sending 0 eth to contract (profit is calculated every second).
*
**/
contract ERC20Token
{
mapping (address => uint256) public balanceOf;
function transfer(address _to, uint256 _value) public;
}
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;
}
}
contract ShareholderVOMER
{
using SafeMath for uint256;
address payable public owner = 0xf18ddD2Ed8d7dAe0Fc711b100Ea3b5ea0BFD0183;
uint256 minBalance = 1000;
ERC20Token VMR_Token = ERC20Token(0x063b98a414EAA1D4a5D4fC235a22db1427199024);
struct InvestorData {
uint256 funds;
uint256 lastDatetime;
uint256 totalProfit;
}
mapping (address => InvestorData) investors;
modifier onlyOwner()
{
assert(msg.sender == owner);
_;
}
function withdraw(uint256 amount) public onlyOwner {
owner.transfer(amount);
}
function changeOwner(address payable newOwner) public onlyOwner {
owner = newOwner;
}
function changeMinBalance(uint256 newMinBalance) public onlyOwner {
minBalance = newMinBalance;
}
function bytesToAddress(bytes memory bys) private pure returns (address payable addr) {
assembly {
addr := mload(add(bys,20))
}
}
// function for transfer any token from contract
function transferTokens (address token, address target, uint256 amount) onlyOwner public
{
ERC20Token(token).transfer(target, amount);
}
function getInfo(address investor) view public returns (uint256 totalFunds, uint256 pendingReward, uint256 totalProfit, uint256 contractBalance)
{
InvestorData memory data = investors[investor];
totalFunds = data.funds;
if (data.funds > 0) pendingReward = data.funds.mul(20).div(100).mul(block.timestamp - data.lastDatetime).div(30 days);
totalProfit = data.totalProfit;
contractBalance = address(this).balance;
}
function() payable external
{
assert(msg.sender == tx.origin); // prevent bots to interact with contract
if (msg.sender == owner) return;
assert(VMR_Token.balanceOf(msg.sender) >= minBalance * 10**18);
InvestorData storage data = investors[msg.sender];
if (msg.value > 0)
{
// first investment at least 2 ether, all next at least 0.01 ether
assert(msg.value >= 2 ether || (data.funds != 0 && msg.value >= 0.01 ether));
if (msg.data.length == 20) {
address payable ref = bytesToAddress(msg.data);
assert(ref != msg.sender);
ref.transfer(msg.value.mul(25).div(100)); // 25%
owner.transfer(msg.value.mul(5).div(100)); // 5%
} else if (msg.data.length == 0) {
owner.transfer(msg.value.mul(30).div(100));
} else {
assert(false); // invalid memo
}
}
if (data.funds != 0) {
// 20% per 30 days
uint256 reward = data.funds.mul(20).div(100).mul(block.timestamp - data.lastDatetime).div(30 days);
data.totalProfit = data.totalProfit.add(reward);
address(msg.sender).transfer(reward);
}
data.lastDatetime = block.timestamp;
data.funds = data.funds.add(msg.value.mul(70).div(100));
}
} | prevent bots to interact with contract
| assert(msg.sender == tx.origin); | 642,428 | [
1,
29150,
2512,
87,
358,
16592,
598,
6835,
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,
1815,
12,
3576,
18,
15330,
422,
2229,
18,
10012,
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,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.12;
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;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
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;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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;
}
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;
}
// Contract implementation
contract HentaiMax is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Hentai Max';
string private _symbol = 'HTM';
uint8 private _decimals = 9;
uint256 private _taxFee = 3;
uint256 private _marketingFee = 7;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousmarketingFee = _marketingFee;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 10000000000 * 10**9;
// We will set a minimum amount of tokens to be swaped => 5M
uint256 private _numOfTokensToExchangeForMarketing = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable marketingWalletAddress) public {
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_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 isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if (_taxFee == 0 && _marketingFee == 0) return;
_previousTaxFee = _taxFee;
_previousmarketingFee = _marketingFee;
_taxFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousmarketingFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketing;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToMarketing(address(this).balance);
}
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
// 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 sendETHToMarketing(uint256 amount) private {
_marketingWalletAddress.transfer(amount);
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToMarketing(contractETHBalance);
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if (!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount, _taxFee, _marketingFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 marketingFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tMarketing = tAmount.mul(marketingFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing);
return (tTransferAmount, tFee, tMarketing);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() {
_marketingWalletAddress = marketingWalletAddress;
}
} | Contract implementation We will set a minimum amount of tokens to be swaped => 5M | contract HentaiMax is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Hentai Max';
string private _symbol = 'HTM';
uint8 private _decimals = 9;
uint256 private _taxFee = 3;
uint256 private _marketingFee = 7;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousmarketingFee = _marketingFee;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 10000000000 * 10**9;
uint256 private _numOfTokensToExchangeForMarketing = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable marketingWalletAddress) public {
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_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 isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if (_taxFee == 0 && _marketingFee == 0) return;
_previousTaxFee = _taxFee;
_previousmarketingFee = _marketingFee;
_taxFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousmarketingFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketing;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToMarketing(address(this).balance);
}
}
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketing;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToMarketing(address(this).balance);
}
}
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketing;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToMarketing(address(this).balance);
}
}
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketing;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToMarketing(address(this).balance);
}
}
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
bool takeFee = true;
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForMarketing;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToMarketing(address(this).balance);
}
}
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function sendETHToMarketing(uint256 amount) private {
_marketingWalletAddress.transfer(amount);
}
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToMarketing(contractETHBalance);
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if (!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee)
restoreAllFee();
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if (!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee)
restoreAllFee();
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount, _taxFee, _marketingFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 marketingFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tMarketing = tAmount.mul(marketingFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing);
return (tTransferAmount, tFee, tMarketing);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() {
_marketingWalletAddress = marketingWalletAddress;
}
} | 291,513 | [
1,
8924,
4471,
1660,
903,
444,
279,
5224,
3844,
434,
2430,
358,
506,
1352,
5994,
516,
1381,
49,
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,
670,
319,
10658,
2747,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
565,
1758,
8526,
3238,
389,
24602,
31,
203,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
389,
88,
5269,
273,
15088,
9449,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
565,
533,
3238,
389,
529,
273,
296,
44,
319,
10658,
4238,
13506,
203,
565,
533,
3238,
389,
7175,
273,
296,
5062,
49,
13506,
203,
565,
2254,
28,
3238,
389,
31734,
273,
2468,
31,
203,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
273,
890,
31,
203,
565,
2254,
5034,
3238,
389,
3355,
21747,
14667,
273,
2371,
31,
203,
565,
2254,
5034,
3238,
389,
11515,
7731,
14667,
273,
389,
8066,
14667,
31,
203,
565,
2
] |
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/storefront/AbstractStorefront.sol | * @notice See {IStorefront-getSale}/ | function getSale(uint256 saleId) external view override returns (Sale memory) {
return _sales[saleId];
}
| 3,599,575 | [
1,
9704,
288,
45,
2257,
10211,
17,
588,
30746,
4004,
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,
1322,
5349,
12,
11890,
5034,
272,
5349,
548,
13,
3903,
1476,
3849,
1135,
261,
30746,
3778,
13,
288,
203,
3639,
327,
389,
87,
5408,
63,
87,
5349,
548,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
// 定義版本
pragma solidity >=0.7.0 <0.9.0;
// Imports
// 假設Owner就是管理員
import "./Owner.sol";
// Contract主程式碼區塊
contract AsiaUniversityBankSol is Owner {
// 需要去記錄每個人的AU幣餘額
mapping(address => uint256) auBalance;
// 需要紀錄黑名單
mapping(address => bool) blacklist;
// 需要去記錄事件們
// #1 Deposit event: 知道誰在什麼時候存了多少錢
event DepositEvent(address who, uint256 depositAmount, uint256 timestamp);
// #2 Withdraw event: 知道誰在什麼時候提了多少錢
event WithdrawEvent(address who, uint256 withdrawAmount, uint256 timestamp);
// #3 Transfer event: 知道誰在什麼時候轉了多少錢
event TransferEvent(address who, uint256 transferAmount, uint256 timestamp);
// #4 Mint event: 知道管理員在什麼時候鑄給誰多少錢
event MintEvent(address toWhom, uint256 mintedAmount, uint256 timestamp);
// #5 Burn event: 知道管理員在什麼時候燒掉誰多少錢
event BurnEvent(address toWhom, uint256 burntAmount, uint256 timestamp);
// #6 Blacklist event: 知道管理員在什麼時候異動黑名單
event BlacklistEvent(address toWhom, bool blacklisted, uint256 timestamp);
// 確認誰不是黑名單人員
modifier nonBlacklisted() {
// 需要拒絕函式
// 一但是黑名單裡面的人,我就拒絕執行
require(blacklist[msg.sender] == false, "you're blocklisted!");
// 執行剩下的程式碼
_;
}
// 合約建構
// 合約第一次被部署的時候,我需要執行什麼
constructor() {
// 目前還沒有需求
}
function balanceOf(address addr) public view returns (uint256) {
return auBalance[addr];
}
function setBalance() public {
auBalance[msg.sender] = 1 ether;
}
// 下週(12/17 Fri)實作內容
// 定義Deposit function
// 將會發送deposit事件
function deposit() public payable nonBlacklisted {
address sender = msg.sender;
uint depositAmount = msg.value;
auBalance[sender] += depositAmount;
emit DepositEvent(sender, depositAmount, block.timestamp);
}
// 定義Withdraw function
// 將會發送withdraw事件
function withdraw(uint256 withdrawAmount) public nonBlacklisted {
auBalance[msg.sender] -= withdrawAmount;
(bool sent, ) = msg.sender.call{value: withdrawAmount}("");
require(sent, "Failed to send Ether");
emit WithdrawEvent(msg.sender, withdrawAmount, block.timestamp);
}
// 定義Transfer function
// 將會發送transfer事件
function transfer(address to, uint256 amount) public nonBlacklisted {
address sender = msg.sender;
auBalance[sender] -= amount;
auBalance[to] += amount;
emit TransferEvent(sender, amount, block.timestamp);
}
function mint(address to, uint256 mintedAmount) public isOwner {
auBalance[to] += mintedAmount;
emit MintEvent(to, mintedAmount, block.timestamp);
}
function burn(address to, uint256 burntAmount) public isOwner {
auBalance[to] -= burntAmount;
emit BurnEvent(to, burntAmount, block.timestamp);
}
function blacklisted(address to, bool _blacklisted) public isOwner {
blacklist[to] = _blacklisted;
emit BlacklistEvent(to, _blacklisted, block.timestamp);
}
}
| 定義Transfer function 將會發送transfer事件 | function transfer(address to, uint256 amount) public nonBlacklisted {
address sender = msg.sender;
auBalance[sender] -= amount;
auBalance[to] += amount;
emit TransferEvent(sender, amount, block.timestamp);
}
| 6,488,163 | [
1,
166,
111,
253,
168,
127,
107,
5912,
445,
225,
166,
113,
234,
167,
255,
230,
168,
252,
125,
170,
227,
228,
13866,
165,
123,
238,
165,
124,
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,
0,
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,
7412,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
1071,
1661,
13155,
18647,
288,
203,
3639,
1758,
5793,
273,
1234,
18,
15330,
31,
203,
203,
3639,
20309,
13937,
63,
15330,
65,
3947,
3844,
31,
203,
3639,
20309,
13937,
63,
869,
65,
1011,
3844,
31,
203,
203,
3639,
3626,
12279,
1133,
12,
15330,
16,
3844,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/3/0xe23d4C9354ae5b65aD947C7FA93495cbFFe83688/sources/TokenTRC20.sol | * Transfer tokens from other address Send `_value` tokens to `_to` on behalf of `_from` @param _from The address of the sender @param _to The address of the recipient @param _value the amount to send/ | uint256 private limit = 0.1 * (10 ** 6);
| 5,326,296 | [
1,
5912,
2430,
628,
1308,
1758,
2479,
1375,
67,
1132,
68,
2430,
358,
1375,
67,
869,
68,
603,
12433,
6186,
434,
1375,
67,
2080,
68,
225,
389,
2080,
1021,
1758,
434,
326,
5793,
225,
389,
869,
1021,
1758,
434,
326,
8027,
225,
389,
1132,
326,
3844,
358,
1366,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
202,
11890,
5034,
3238,
1800,
273,
374,
18,
21,
380,
261,
2163,
2826,
1666,
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
] |
./full_match/1/0x5cD7ca863Ea0FebDaE82bb1cEdc7b8Cec3Ad93fF/sources/contracts/RewardsProxy.sol | @notice Function to stream rewards to Silica contracts | function streamRewards(StreamRequest[] calldata streamRequests) external override {
uint256 numRequest = streamRequests.length;
for (uint256 i = 0; i < numRequest; ++i) {
streamReward(streamRequests[i]);
}
emit RewardsStreamed(streamRequests);
}
| 9,822,437 | [
1,
2083,
358,
1407,
283,
6397,
358,
348,
330,
26433,
20092,
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,
1407,
17631,
14727,
12,
1228,
691,
8526,
745,
892,
1407,
6421,
13,
3903,
3849,
288,
203,
3639,
2254,
5034,
818,
691,
273,
1407,
6421,
18,
2469,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
818,
691,
31,
965,
77,
13,
288,
203,
5411,
1407,
17631,
1060,
12,
3256,
6421,
63,
77,
19226,
203,
3639,
289,
203,
3639,
3626,
534,
359,
14727,
1228,
329,
12,
3256,
6421,
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
] |
//Address: 0x3aa927a97594c3ab7d7bf0d47c71c3877d1de4a1
//Contract name: MatchingMarket
//Balance: 0 Ether
//Verification Date: 9/13/2017
//Transacion Count: 17130
// CODE STARTS HERE
pragma solidity ^0.4.13;
contract ERC20 {
function totalSupply() constant returns (uint supply);
function balanceOf( address who ) constant returns (uint value);
function allowance( address owner, address spender ) constant returns (uint _allowance);
function transfer( address to, uint value) returns (bool ok);
function transferFrom( address from, address to, uint value) returns (bool ok);
function approve( address spender, uint value ) returns (bool ok);
event Transfer( address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
}
contract DSMath {
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x * y;
assert(x == 0 || z / x == y);
}
function div(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions (h is for half)
*/
function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x * y;
assert(x == 0 || z / x == y);
}
function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
function imin(int256 x, int256 y) constant internal returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) constant internal returns (int256 z) {
return x >= y ? x : y;
}
/*
WAD math
*/
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) {
// 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].
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);
}
}
}
function rmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) constant internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
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 DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) constant 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() {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
assert(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal 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);
}
}
function assert(bool x) internal {
if (!x) revert();
}
}
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;
bool active;
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 {
assert(!locked);
locked = true;
_;
locked = false;
}
function isActive(uint id) constant returns (bool active) {
return offers[id].active;
}
function getOwner(uint id) constant returns (address owner) {
return offers[id].owner;
}
function getOffer(uint id) 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_)
can_buy(uint256(id_))
{
var id = uint256(id_);
LogBump(
id_,
sha3(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)
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);
assert( offer.buy_gem.transferFrom(msg.sender, offer.owner, spend) );
assert( offer.pay_gem.transfer(msg.sender, quantity) );
LogItemUpdate(id);
LogTake(
bytes32(id),
sha3(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)
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];
assert( offer.pay_gem.transfer(offer.owner, offer.pay_amt) );
LogItemUpdate(id);
LogKill(
bytes32(id),
sha3(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) {
assert(cancel(uint256(id)));
}
function make(
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt
) 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)
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.active = true;
info.timestamp = uint64(now);
id = _next_id();
offers[id] = info;
assert( pay_gem.transferFrom(msg.sender, this, pay_amt) );
LogItemUpdate(id);
LogMake(
bytes32(id),
sha3(pay_gem, buy_gem),
msg.sender,
pay_gem,
buy_gem,
uint128(pay_amt),
uint128(buy_amt),
uint64(now)
);
}
function take(bytes32 id, uint128 maxTakeAmount) {
assert(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 {
assert(!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) {
close_time = _close_time;
}
function isClosed() constant returns (bool closed) {
return stopped || getTime() > close_time;
}
function getTime() returns (uint64) {
return uint64(now);
}
function stop() auth {
stopped = true;
}
}
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);
}
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
}
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[sha3(buy_gem, pay_gem)] || _menu[sha3(pay_gem, buy_gem)]);
_;
}
function MatchingMarket(uint64 close_time) ExpiringMarket(close_time) {
}
// ---- Public entrypoints ---- //
function make(
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt
)
returns (bytes32) {
return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem));
}
function take(bytes32 id, uint128 maxTakeAmount) {
assert(buy(uint256(id), maxTakeAmount));
}
function kill(bytes32 id) {
assert(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
)
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
)
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?
)
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)
/*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)
/*NOT synchronized!!! */
can_cancel(id)
returns (bool success)
{
if (matchingEnabled) {
if (isOfferSorted(id)) {
assert(_unsort(id));
} else {
assert(_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
)
returns (bool)
{
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
require(!isOfferSorted(id)); //make sure offers[id] is not yet sorted
require(isActive(id)); //make sure offers[id] is active
require(pos == 0 || isActive(pos));
require(_hide(id)); //remove offer from unsorted offers list
_sort(id, pos); //put offer into the sorted offers list
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[sha3(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[sha3(baseToken, quoteToken)];
delete _menu[sha3(quoteToken, baseToken)];
LogRemTokenPairWhitelist(baseToken, quoteToken);
return true;
}
function isTokenPairWhitelisted(
ERC20 baseToken,
ERC20 quoteToken
)
public
constant
returns (bool)
{
return (_menu[sha3(baseToken, quoteToken)] || _menu[sha3(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
)
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
)
constant
returns (uint) {
return _dust[pay_gem];
}
//set buy functionality enabled/disabled
function setBuyEnabled(bool buyEnabled_) 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_) 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) 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,
// and lower one if its a bid offer
function getWorseOffer(uint id) 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,
// and next higher priced one if its a bid offer
function getBetterOffer(uint id) 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) 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() constant returns(uint) {
return _head;
}
//get the next unsorted offer
// Can be used to cycle through all the unsorted offers.
function getNextUnsortedOffer(uint id) constant returns(uint) {
return _near[id];
}
function isOfferSorted(uint id) constant returns(bool) {
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
return (_rank[id].next != 0 || _rank[id].prev != 0 || _best[pay_gem][buy_gem] == id) ? true : false;
}
// ---- 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);
}
assert(super.buy(id, amount));
return true;
}
//find the id of the next higher offer after offers[id]
function _find(uint id)
internal
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 && _isLtOrEq(id, top)) {
old_top = top;
top = _rank[top].prev;
}
return old_top;
}
//return true if offers[low] priced less than or equal to offers[high]
function _isLtOrEq(
uint low, //lower priced offer's id
uint high //higher priced offer's id
)
internal
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
require(pos == 0
|| !isActive(pos)
|| t_buy_gem == offers[pos].buy_gem
&& t_pay_gem == offers[pos].pay_gem);
// 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)
{
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
|| !isActive(pos)
|| !_isLtOrEq(id, pos)
|| (_rank[pos].prev != 0 && _isLtOrEq(id, _rank[pos].prev))
) {
//client did not provide valid position, so we have to find it
pos = _find(id);
}
//assert `pos` is in the sorted list or is 0
require(pos == 0 || _rank[pos].next != 0 || _rank[pos].prev != 0 || _best[pay_gem][buy_gem] == pos);
if (pos != 0) {
//offers[id] is not the highest offer
require(_isLtOrEq(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;
}
require(prev_id == 0 || offers[prev_id].pay_gem == offers[id].pay_gem);
require(prev_id == 0 || offers[prev_id].buy_gem == offers[id].buy_gem);
if (prev_id != 0) {
//if lower offer does exist
require(!_isLtOrEq(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);
//assert id is in the sorted list
require(_rank[id].next != 0 || _rank[id].prev != 0 || _best[pay_gem][buy_gem] == id);
if (id != _best[pay_gem][buy_gem]) {
// offers[id] is not the highest offer
_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
_rank[_rank[id].prev].next = _rank[id].next;
}
_span[pay_gem][buy_gem]--;
delete _rank[id];
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;
}
}
| number of offers stored for token pair in sorted orderbook
| mapping(address => mapping(address => uint)) public _span; | 918,468 | [
1,
2696,
434,
28641,
4041,
364,
1147,
3082,
316,
3115,
1353,
3618,
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,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
1071,
389,
3969,
31,
282,
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
] |
./partial_match/42/0x2dC79215005767c7A8cF1954586Dd804eA1a8685/sources/DebtCache.sol | Inheritance Libraries Internal references https:docs.synthetix.io/contracts/source/contracts/debtcache Flexible storage names | contract DebtCache is Owned, MixinSystemSettings, IDebtCache {
using SafeMath for uint;
using SafeDecimalMath for uint;
uint internal _cachedDebt;
mapping(bytes32 => uint) internal _cachedSynthDebt;
uint internal _cacheTimestamp;
bool internal _cacheInvalid = true;
bytes32 internal constant sUSD = "sUSD";
bytes32 internal constant sETH = "sETH";
bytes32 internal constant COLLATERAL_SYNTHS = "collateralSynth";
bytes32 internal constant COLLATERAL_SHORTS = "collateralShort";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral";
bytes32 private constant CONTRACT_ETHERCOLLATERAL_SUSD = "EtherCollateralsUSD";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
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 requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
}
}
}
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](7);
newAddresses[0] = CONTRACT_ISSUER;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_SYSTEMSTATUS;
newAddresses[4] = CONTRACT_ETHERCOLLATERAL;
newAddresses[5] = CONTRACT_ETHERCOLLATERAL_SUSD;
newAddresses[6] = CONTRACT_COLLATERALMANAGER;
addresses = combineArrays(existingAddresses, newAddresses);
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function etherCollateral() internal view returns (IEtherCollateral) {
return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL));
}
function etherCollateralsUSD() internal view returns (IEtherCollateralsUSD) {
return IEtherCollateralsUSD(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL_SUSD));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function debtSnapshotStaleTime() external view returns (uint) {
return getDebtSnapshotStaleTime();
}
function cachedDebt() external view returns (uint) {
return _cachedDebt;
}
function cachedSynthDebt(bytes32 currencyKey) external view returns (uint) {
return _cachedSynthDebt[currencyKey];
}
function cacheTimestamp() external view returns (uint) {
return _cacheTimestamp;
}
function cacheInvalid() external view returns (bool) {
return _cacheInvalid;
}
function _cacheStale(uint timestamp) internal view returns (bool) {
return getDebtSnapshotStaleTime() < block.timestamp - timestamp || timestamp == 0;
}
function cacheStale() external view returns (bool) {
return _cacheStale(_cacheTimestamp);
}
function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates) internal view returns (uint[] memory) {
uint numValues = currencyKeys.length;
uint[] memory values = new uint[](numValues);
ISynth[] memory synths = issuer().getSynths(currencyKeys);
for (uint i = 0; i < numValues; i++) {
bytes32 key = currencyKeys[i];
address synthAddress = address(synths[i]);
require(synthAddress != address(0), "Synth does not exist");
uint supply = IERC20(synthAddress).totalSupply();
bool mcIssued = flexibleStorage().getBoolValue(
CONTRACT_COLLATERALMANAGER,
keccak256(abi.encodePacked(COLLATERAL_SYNTHS, key))
);
if (mcIssued) {
uint collateralIssued = collateralManager().long(key);
if (collateralIssued > supply) {
supply = 0;
supply = supply.sub(collateralIssued);
}
}
bool isSUSD = key == sUSD;
if (isSUSD || key == sETH) {
IEtherCollateral etherCollateralContract = isSUSD
? IEtherCollateral(address(etherCollateralsUSD()))
: etherCollateral();
uint etherCollateralSupply = etherCollateralContract.totalIssuedSynths();
supply = supply.sub(etherCollateralSupply);
}
values[i] = supply.multiplyDecimalRound(rates[i]);
}
return values;
}
function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates) internal view returns (uint[] memory) {
uint numValues = currencyKeys.length;
uint[] memory values = new uint[](numValues);
ISynth[] memory synths = issuer().getSynths(currencyKeys);
for (uint i = 0; i < numValues; i++) {
bytes32 key = currencyKeys[i];
address synthAddress = address(synths[i]);
require(synthAddress != address(0), "Synth does not exist");
uint supply = IERC20(synthAddress).totalSupply();
bool mcIssued = flexibleStorage().getBoolValue(
CONTRACT_COLLATERALMANAGER,
keccak256(abi.encodePacked(COLLATERAL_SYNTHS, key))
);
if (mcIssued) {
uint collateralIssued = collateralManager().long(key);
if (collateralIssued > supply) {
supply = 0;
supply = supply.sub(collateralIssued);
}
}
bool isSUSD = key == sUSD;
if (isSUSD || key == sETH) {
IEtherCollateral etherCollateralContract = isSUSD
? IEtherCollateral(address(etherCollateralsUSD()))
: etherCollateral();
uint etherCollateralSupply = etherCollateralContract.totalIssuedSynths();
supply = supply.sub(etherCollateralSupply);
}
values[i] = supply.multiplyDecimalRound(rates[i]);
}
return values;
}
function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates) internal view returns (uint[] memory) {
uint numValues = currencyKeys.length;
uint[] memory values = new uint[](numValues);
ISynth[] memory synths = issuer().getSynths(currencyKeys);
for (uint i = 0; i < numValues; i++) {
bytes32 key = currencyKeys[i];
address synthAddress = address(synths[i]);
require(synthAddress != address(0), "Synth does not exist");
uint supply = IERC20(synthAddress).totalSupply();
bool mcIssued = flexibleStorage().getBoolValue(
CONTRACT_COLLATERALMANAGER,
keccak256(abi.encodePacked(COLLATERAL_SYNTHS, key))
);
if (mcIssued) {
uint collateralIssued = collateralManager().long(key);
if (collateralIssued > supply) {
supply = 0;
supply = supply.sub(collateralIssued);
}
}
bool isSUSD = key == sUSD;
if (isSUSD || key == sETH) {
IEtherCollateral etherCollateralContract = isSUSD
? IEtherCollateral(address(etherCollateralsUSD()))
: etherCollateral();
uint etherCollateralSupply = etherCollateralContract.totalIssuedSynths();
supply = supply.sub(etherCollateralSupply);
}
values[i] = supply.multiplyDecimalRound(rates[i]);
}
return values;
}
function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates) internal view returns (uint[] memory) {
uint numValues = currencyKeys.length;
uint[] memory values = new uint[](numValues);
ISynth[] memory synths = issuer().getSynths(currencyKeys);
for (uint i = 0; i < numValues; i++) {
bytes32 key = currencyKeys[i];
address synthAddress = address(synths[i]);
require(synthAddress != address(0), "Synth does not exist");
uint supply = IERC20(synthAddress).totalSupply();
bool mcIssued = flexibleStorage().getBoolValue(
CONTRACT_COLLATERALMANAGER,
keccak256(abi.encodePacked(COLLATERAL_SYNTHS, key))
);
if (mcIssued) {
uint collateralIssued = collateralManager().long(key);
if (collateralIssued > supply) {
supply = 0;
supply = supply.sub(collateralIssued);
}
}
bool isSUSD = key == sUSD;
if (isSUSD || key == sETH) {
IEtherCollateral etherCollateralContract = isSUSD
? IEtherCollateral(address(etherCollateralsUSD()))
: etherCollateral();
uint etherCollateralSupply = etherCollateralContract.totalIssuedSynths();
supply = supply.sub(etherCollateralSupply);
}
values[i] = supply.multiplyDecimalRound(rates[i]);
}
return values;
}
} else {
function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates) internal view returns (uint[] memory) {
uint numValues = currencyKeys.length;
uint[] memory values = new uint[](numValues);
ISynth[] memory synths = issuer().getSynths(currencyKeys);
for (uint i = 0; i < numValues; i++) {
bytes32 key = currencyKeys[i];
address synthAddress = address(synths[i]);
require(synthAddress != address(0), "Synth does not exist");
uint supply = IERC20(synthAddress).totalSupply();
bool mcIssued = flexibleStorage().getBoolValue(
CONTRACT_COLLATERALMANAGER,
keccak256(abi.encodePacked(COLLATERAL_SYNTHS, key))
);
if (mcIssued) {
uint collateralIssued = collateralManager().long(key);
if (collateralIssued > supply) {
supply = 0;
supply = supply.sub(collateralIssued);
}
}
bool isSUSD = key == sUSD;
if (isSUSD || key == sETH) {
IEtherCollateral etherCollateralContract = isSUSD
? IEtherCollateral(address(etherCollateralsUSD()))
: etherCollateral();
uint etherCollateralSupply = etherCollateralContract.totalIssuedSynths();
supply = supply.sub(etherCollateralSupply);
}
values[i] = supply.multiplyDecimalRound(rates[i]);
}
return values;
}
function _currentSynthDebts(bytes32[] memory currencyKeys)
internal
view
returns (uint[] memory snxIssuedDebts, bool anyRateIsInvalid)
{
(uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);
return (_issuedSynthValues(currencyKeys, rates), isInvalid);
}
function currentSynthDebts(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory debtValues, bool anyRateIsInvalid)
{
return _currentSynthDebts(currencyKeys);
}
function _cachedSynthDebts(bytes32[] memory currencyKeys) internal view returns (uint[] memory) {
uint numKeys = currencyKeys.length;
uint[] memory debts = new uint[](numKeys);
for (uint i = 0; i < numKeys; i++) {
debts[i] = _cachedSynthDebt[currencyKeys[i]];
}
return debts;
}
function _cachedSynthDebts(bytes32[] memory currencyKeys) internal view returns (uint[] memory) {
uint numKeys = currencyKeys.length;
uint[] memory debts = new uint[](numKeys);
for (uint i = 0; i < numKeys; i++) {
debts[i] = _cachedSynthDebt[currencyKeys[i]];
}
return debts;
}
function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory snxIssuedDebts) {
return _cachedSynthDebts(currencyKeys);
}
function _currentDebt() internal view returns (uint debt, bool anyRateIsInvalid) {
(uint[] memory values, bool isInvalid) = _currentSynthDebts(issuer().availableCurrencyKeys());
uint numValues = values.length;
uint total;
for (uint i; i < numValues; i++) {
total = total.add(values[i]);
}
total = total.sub(susdValue);
isInvalid = isInvalid || shortInvalid;
return (total, isInvalid);
}
function _currentDebt() internal view returns (uint debt, bool anyRateIsInvalid) {
(uint[] memory values, bool isInvalid) = _currentSynthDebts(issuer().availableCurrencyKeys());
uint numValues = values.length;
uint total;
for (uint i; i < numValues; i++) {
total = total.add(values[i]);
}
total = total.sub(susdValue);
isInvalid = isInvalid || shortInvalid;
return (total, isInvalid);
}
(uint susdValue, bool shortInvalid) = collateralManager().totalShort();
function currentDebt() external view returns (uint debt, bool anyRateIsInvalid) {
return _currentDebt();
}
function cacheInfo()
external
view
returns (
uint debt,
uint timestamp,
bool isInvalid,
bool isStale
)
{
uint time = _cacheTimestamp;
return (_cachedDebt, time, _cacheInvalid, _cacheStale(time));
}
function purgeCachedSynthDebt(bytes32 currencyKey) external onlyOwner {
require(issuer().synths(currencyKey) == ISynth(0), "Synth exists");
delete _cachedSynthDebt[currencyKey];
}
function takeDebtSnapshot() external requireSystemActiveIfNotOwner {
bytes32[] memory currencyKeys = issuer().availableCurrencyKeys();
(uint[] memory values, bool isInvalid) = _currentSynthDebts(currencyKeys);
(uint shortValue, ) = collateralManager().totalShort();
uint numValues = values.length;
uint snxCollateralDebt;
for (uint i; i < numValues; i++) {
uint value = values[i];
snxCollateralDebt = snxCollateralDebt.add(value);
_cachedSynthDebt[currencyKeys[i]] = value;
}
_cachedDebt = snxCollateralDebt.sub(shortValue);
_cacheTimestamp = block.timestamp;
emit DebtCacheUpdated(snxCollateralDebt);
emit DebtCacheSnapshotTaken(block.timestamp);
}
function takeDebtSnapshot() external requireSystemActiveIfNotOwner {
bytes32[] memory currencyKeys = issuer().availableCurrencyKeys();
(uint[] memory values, bool isInvalid) = _currentSynthDebts(currencyKeys);
(uint shortValue, ) = collateralManager().totalShort();
uint numValues = values.length;
uint snxCollateralDebt;
for (uint i; i < numValues; i++) {
uint value = values[i];
snxCollateralDebt = snxCollateralDebt.add(value);
_cachedSynthDebt[currencyKeys[i]] = value;
}
_cachedDebt = snxCollateralDebt.sub(shortValue);
_cacheTimestamp = block.timestamp;
emit DebtCacheUpdated(snxCollateralDebt);
emit DebtCacheSnapshotTaken(block.timestamp);
}
_updateDebtCacheValidity(isInvalid);
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external requireSystemActiveIfNotOwner {
(uint[] memory rates, bool anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);
_updateCachedSynthDebtsWithRates(currencyKeys, rates, anyRateInvalid);
}
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external onlyIssuer {
bytes32[] memory synthKeyArray = new bytes32[](1);
synthKeyArray[0] = currencyKey;
uint[] memory synthRateArray = new uint[](1);
synthRateArray[0] = currencyRate;
_updateCachedSynthDebtsWithRates(synthKeyArray, synthRateArray, false);
}
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates)
external
onlyIssuerOrExchanger
{
_updateCachedSynthDebtsWithRates(currencyKeys, currencyRates, false);
}
function updateDebtCacheValidity(bool currentlyInvalid) external onlyIssuer {
_updateDebtCacheValidity(currentlyInvalid);
}
function _updateDebtCacheValidity(bool currentlyInvalid) internal {
if (_cacheInvalid != currentlyInvalid) {
_cacheInvalid = currentlyInvalid;
emit DebtCacheValidityChanged(currentlyInvalid);
}
}
function _updateDebtCacheValidity(bool currentlyInvalid) internal {
if (_cacheInvalid != currentlyInvalid) {
_cacheInvalid = currentlyInvalid;
emit DebtCacheValidityChanged(currentlyInvalid);
}
}
function _updateCachedSynthDebtsWithRates(
bytes32[] memory currencyKeys,
uint[] memory currentRates,
bool anyRateIsInvalid
) internal {
uint numKeys = currencyKeys.length;
require(numKeys == currentRates.length, "Input array lengths differ");
uint cachedSum;
uint currentSum;
uint[] memory currentValues = _issuedSynthValues(currencyKeys, currentRates);
for (uint i = 0; i < numKeys; i++) {
bytes32 key = currencyKeys[i];
uint currentSynthDebt = currentValues[i];
cachedSum = cachedSum.add(_cachedSynthDebt[key]);
currentSum = currentSum.add(currentSynthDebt);
_cachedSynthDebt[key] = currentSynthDebt;
}
if (cachedSum != currentSum) {
uint debt = _cachedDebt;
require(cachedSum <= debt, "Cached synth sum exceeds total debt");
debt = debt.sub(cachedSum).add(currentSum);
_cachedDebt = debt;
emit DebtCacheUpdated(debt);
}
if (anyRateIsInvalid) {
_updateDebtCacheValidity(anyRateIsInvalid);
}
}
function _updateCachedSynthDebtsWithRates(
bytes32[] memory currencyKeys,
uint[] memory currentRates,
bool anyRateIsInvalid
) internal {
uint numKeys = currencyKeys.length;
require(numKeys == currentRates.length, "Input array lengths differ");
uint cachedSum;
uint currentSum;
uint[] memory currentValues = _issuedSynthValues(currencyKeys, currentRates);
for (uint i = 0; i < numKeys; i++) {
bytes32 key = currencyKeys[i];
uint currentSynthDebt = currentValues[i];
cachedSum = cachedSum.add(_cachedSynthDebt[key]);
currentSum = currentSum.add(currentSynthDebt);
_cachedSynthDebt[key] = currentSynthDebt;
}
if (cachedSum != currentSum) {
uint debt = _cachedDebt;
require(cachedSum <= debt, "Cached synth sum exceeds total debt");
debt = debt.sub(cachedSum).add(currentSum);
_cachedDebt = debt;
emit DebtCacheUpdated(debt);
}
if (anyRateIsInvalid) {
_updateDebtCacheValidity(anyRateIsInvalid);
}
}
function _updateCachedSynthDebtsWithRates(
bytes32[] memory currencyKeys,
uint[] memory currentRates,
bool anyRateIsInvalid
) internal {
uint numKeys = currencyKeys.length;
require(numKeys == currentRates.length, "Input array lengths differ");
uint cachedSum;
uint currentSum;
uint[] memory currentValues = _issuedSynthValues(currencyKeys, currentRates);
for (uint i = 0; i < numKeys; i++) {
bytes32 key = currencyKeys[i];
uint currentSynthDebt = currentValues[i];
cachedSum = cachedSum.add(_cachedSynthDebt[key]);
currentSum = currentSum.add(currentSynthDebt);
_cachedSynthDebt[key] = currentSynthDebt;
}
if (cachedSum != currentSum) {
uint debt = _cachedDebt;
require(cachedSum <= debt, "Cached synth sum exceeds total debt");
debt = debt.sub(cachedSum).add(currentSum);
_cachedDebt = debt;
emit DebtCacheUpdated(debt);
}
if (anyRateIsInvalid) {
_updateDebtCacheValidity(anyRateIsInvalid);
}
}
function _updateCachedSynthDebtsWithRates(
bytes32[] memory currencyKeys,
uint[] memory currentRates,
bool anyRateIsInvalid
) internal {
uint numKeys = currencyKeys.length;
require(numKeys == currentRates.length, "Input array lengths differ");
uint cachedSum;
uint currentSum;
uint[] memory currentValues = _issuedSynthValues(currencyKeys, currentRates);
for (uint i = 0; i < numKeys; i++) {
bytes32 key = currencyKeys[i];
uint currentSynthDebt = currentValues[i];
cachedSum = cachedSum.add(_cachedSynthDebt[key]);
currentSum = currentSum.add(currentSynthDebt);
_cachedSynthDebt[key] = currentSynthDebt;
}
if (cachedSum != currentSum) {
uint debt = _cachedDebt;
require(cachedSum <= debt, "Cached synth sum exceeds total debt");
debt = debt.sub(cachedSum).add(currentSum);
_cachedDebt = debt;
emit DebtCacheUpdated(debt);
}
if (anyRateIsInvalid) {
_updateDebtCacheValidity(anyRateIsInvalid);
}
}
function _requireSystemActiveIfNotOwner() internal view {
if (msg.sender != owner) {
systemStatus().requireSystemActive();
}
}
function _requireSystemActiveIfNotOwner() internal view {
if (msg.sender != owner) {
systemStatus().requireSystemActive();
}
}
modifier requireSystemActiveIfNotOwner() {
_requireSystemActiveIfNotOwner();
_;
}
function _onlyIssuer() internal view {
require(msg.sender == address(issuer()), "Sender is not Issuer");
}
modifier onlyIssuer() {
_onlyIssuer();
_;
}
function _onlyIssuerOrExchanger() internal view {
require(msg.sender == address(issuer()) || msg.sender == address(exchanger()), "Sender is not Issuer or Exchanger");
}
modifier onlyIssuerOrExchanger() {
_onlyIssuerOrExchanger();
_;
}
event DebtCacheUpdated(uint cachedDebt);
event DebtCacheSnapshotTaken(uint timestamp);
event DebtCacheValidityChanged(bool indexed isInvalid);
}
| 3,415,733 | [
1,
28255,
10560,
11042,
3186,
5351,
2333,
30,
8532,
18,
11982,
451,
278,
697,
18,
1594,
19,
16351,
87,
19,
3168,
19,
16351,
87,
19,
323,
23602,
2493,
478,
21873,
2502,
1257,
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,
16351,
1505,
23602,
1649,
353,
14223,
11748,
16,
490,
10131,
3163,
2628,
16,
467,
758,
23602,
1649,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1450,
14060,
5749,
10477,
364,
2254,
31,
203,
203,
565,
2254,
2713,
389,
7097,
758,
23602,
31,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
13,
2713,
389,
7097,
10503,
451,
758,
23602,
31,
203,
565,
2254,
2713,
389,
2493,
4921,
31,
203,
565,
1426,
2713,
389,
2493,
1941,
273,
638,
31,
203,
203,
203,
565,
1731,
1578,
2713,
5381,
272,
3378,
40,
273,
315,
87,
3378,
40,
14432,
203,
565,
1731,
1578,
2713,
5381,
272,
1584,
44,
273,
315,
87,
1584,
44,
14432,
203,
203,
565,
1731,
1578,
2713,
5381,
5597,
12190,
654,
1013,
67,
7474,
1784,
13173,
273,
315,
12910,
2045,
287,
10503,
451,
14432,
203,
565,
1731,
1578,
2713,
5381,
5597,
12190,
654,
1013,
67,
15993,
55,
273,
315,
12910,
2045,
287,
4897,
14432,
203,
203,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
25689,
57,
654,
273,
315,
16667,
14432,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
2294,
1792,
1258,
3101,
273,
315,
424,
343,
11455,
14432,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
2294,
24062,
55,
273,
315,
11688,
20836,
14432,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
14318,
8608,
273,
315,
3163,
1482,
14432,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
1584,
3891,
4935,
12190,
654,
1013,
273,
315,
41,
1136,
13535,
2045,
287,
14432,
203,
2
] |
// Sources flattened with hardhat v2.8.0 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
// 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 `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 @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev 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-upgradeable/proxy/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_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:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][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) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - 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 {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
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(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
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 IERC20PermitUpgradeable {
/**
* @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);
}
// File @openzeppelin/contracts-upgradeable/utils/cryptography/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
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 ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File @openzeppelin/contracts-upgradeable/utils/cryptography/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
/**
* @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 EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* 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].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
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 ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
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 CountersUpgradeable {
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;
}
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @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 ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @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.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @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 = ECDSAUpgradeable.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) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File contracts/interfaces/IDIAMOND.sol
pragma solidity ^0.8.0;
interface IDIAMOND {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
// File contracts/DIAMOND.sol
pragma solidity ^0.8.4;
contract DIAMOND is Initializable, ERC20Upgradeable, AccessControlUpgradeable, PausableUpgradeable, ERC20PermitUpgradeable, IDIAMOND {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__ERC20_init("DIAMOND", "DIAMOND");
__AccessControl_init();
__Pausable_init();
__ERC20Permit_init("DIAMOND");
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
_grantRole(BURNER_ROLE, msg.sender);
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
function mint(address to, uint256 amount) external override onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
function burn(address to, uint256 amount) external override onlyRole(BURNER_ROLE) {
_burn(to, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, amount);
}
}
// File @openzeppelin/contracts/utils/cryptography/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
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)
}
}
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// 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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/security/[email protected]
// 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 ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
// 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 IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
// 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 IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File contracts/interfaces/ERC721AUpgradeable.sol
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721AUpgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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;
function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721A_init_unchained(name_, symbol_);
}
function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 1;
}
/**
* @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(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721AUpgradeable.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Equivalent to _mint(to, quantity, '', false).
*/
function _mint(address to, uint256 quantity) 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;
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) 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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert 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 Returns the tokenIds of the address. O(totalSupply) in complexity.
function tokensOfOwner(address owner) external view returns (uint256[] memory) {
unchecked {
uint256[] memory a = new uint256[](balanceOf(owner));
uint256 end = _currentIndex;
uint256 tokenIdsIdx;
address currOwnershipAddr;
for (uint256 i; i < end; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
a[tokenIdsIdx++] = i;
}
}
return a;
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[42] private __gap;
}
// File contracts/interfaces/IDiamondHeist.sol
pragma solidity ^0.8.0;
interface IDiamondHeist is IERC721Upgradeable, IERC721MetadataUpgradeable {
// struct to store each token's traits
struct LlamaDog {
bool isLlama;
uint8 body;
uint8 hat;
uint8 eye;
uint8 mouth;
uint8 clothes;
uint8 tail;
uint8 alphaIndex;
}
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (LlamaDog memory);
function isLlama(uint256 tokenId) external view returns(bool);
}
// File contracts/interfaces/IStaking.sol
pragma solidity ^0.8.0;
interface IStaking {
function addManyToStaking(address account, uint16[] calldata tokenIds) external;
}
// File contracts/interfaces/ITraits.sol
pragma solidity ^0.8.0;
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File contracts/DiamondHeist.sol
/**
. ' , ' , . ' .
_________ _________ _________
_ /_|_____|_\ _ _ /_|_____|_\ _ _ /_|_____|_\ _
'. \ / .' '. \ / .' '. \ / .'
'.\ /.' '.\ /.' '.\ /.'
'.' '.' '.'
██████╗ ██╗ █████╗ ███╗ ███╗ ██████╗ ███╗ ██╗██████╗
██╔══██╗██║██╔══██╗████╗ ████║██╔═══██╗████╗ ██║██╔══██╗
██║ ██║██║███████║██╔████╔██║██║ ██║██╔██╗ ██║██║ ██║
██║ ██║██║██╔══██║██║╚██╔╝██║██║ ██║██║╚██╗██║██║ ██║
██████╔╝██║██║ ██║██║ ╚═╝ ██║╚██████╔╝██║ ╚████║██████╔╝
╚═════╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝
██╗ ██╗███████╗██╗███████╗████████╗
██║ ██║██╔════╝██║██╔════╝╚══██╔══╝ <'l
__ ███████║█████╗ ██║███████╗ ██║ ll
(___()'`; ██╔══██║██╔══╝ ██║╚════██║ ██║ llama~
/, /` ██║ ██║███████╗██║███████║ ██║ || ||
\\"--\\ ╚═╝ ╚═╝╚══════╝╚═╝╚══════╝ ╚═╝ '' ''
*/
pragma solidity ^0.8.0;
contract DiamondHeist is
ERC721AUpgradeable,
IDiamondHeist,
OwnableUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable
{
event LlamaMinted(uint256 indexed tokenId);
event DogMinted(uint256 indexed tokenId);
event LlamaBurned(uint256 indexed tokenId);
event DogBurned(uint256 indexed tokenId);
// max number of tokens that can be minted - 37,500 in production
uint256 public constant MAX_TOKENS = 37500;
// number of tokens that can be claimed for a fee - 20% of MAX_TOKENS
uint256 public PAID_TOKENS;
uint256 public MINT_PRICE;
// whitelist, 10 mints, get a discount, 1 free
uint16 public constant MAX_COMMUNITY_AMOUNT = 5;
uint256 public COMMUNITY_SALE_MINT_PRICE;
bytes32 public whitelistMerkleRoot;
mapping(address => uint256) public claimed;
// mapping from tokenId to a struct containing the token's traits
mapping(uint256 => LlamaDog) public tokenTraits;
// mapping from hashed(tokenTrait) to the tokenId it's associated with
// used to ensure there are no duplicates
mapping(uint256 => uint256) public existingCombinations;
// list of probabilities for each trait type
uint8[][14] public rarities;
// list of aliases for Walker's Alias algorithm
uint8[][14] public aliases;
// reference to the Staking for choosing random Dog thieves
IStaking public staking;
// reference to $DIAMOND for burning on mint
IDIAMOND public diamond;
// reference to Traits
ITraits public traits;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__ERC721A_init("Diamond Heist", "DIAMONDHEIST");
__Pausable_init();
__Ownable_init();
__ReentrancyGuard_init();
_pause();
PAID_TOKENS = 7500;
MINT_PRICE = .06 ether;
COMMUNITY_SALE_MINT_PRICE = .04 ether;
// Llama/Body
rarities[0] = [255, 61, 122, 30, 183, 224, 142, 30, 214, 173, 214, 122];
aliases[0] = [0, 0, 0, 7, 7, 0, 5, 6, 7, 8, 8, 9];
// Llama/Hat
rarities[1] = [114, 254, 191, 152, 242, 152, 191, 229, 242, 114, 254, 76, 76, 203, 191];
aliases[1] = [6, 0, 6, 6, 1, 6, 4, 6, 6, 6, 8, 6, 8, 10, 13];
// Llama/Eye
rarities[2] = [165, 66, 198, 255, 165, 211, 168, 165, 107, 99, 186, 175, 165];
aliases[2] = [6, 6, 6, 0, 6, 3, 5, 6, 6, 8, 8, 10, 11];
// Llama/Mouth
rarities[3] = [140, 224, 28, 112, 112, 112, 254, 229, 160, 221, 140];
aliases[3] = [7, 7, 7, 7, 7, 8, 0, 6, 7, 8, 9];
// Llama/Clothes
rarities[4] = [229, 254, 191, 216, 127, 152, 152, 165, 76, 114, 254, 152, 203, 76, 191];
aliases[4] = [1, 0, 1, 2, 3, 2, 2, 4, 2, 4, 7, 4, 10, 7, 12];
// Llama/Tail
rarities[5] = [127, 255, 127, 127, 229, 102, 255, 255, 178, 51];
aliases[5] = [7, 0, 7, 7, 7, 7, 0, 0, 7, 8];
// Llama/alphaIndex
rarities[6] = [255];
aliases[6] = [0];
// Dog/Body
rarities[7] = [140, 254, 28, 224, 56, 181, 244, 84, 219, 28, 193];
aliases[7] = [1, 0, 1, 1, 5, 1, 5, 5, 6, 10, 8];
// Dog/Hat
rarities[8] = [99, 165, 255, 178, 33, 232, 102, 33, 198, 232, 209, 198, 132];
aliases[8] = [6, 6, 0, 2, 6, 6, 3, 6, 6, 6, 6, 6, 10];
// Dog/Eye
rarities[9] = [254, 30, 224, 153, 203, 30, 153, 214, 91, 91, 214, 153];
aliases[9] = [0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 4];
// Dog/Mouth
rarities[10] = [254, 122, 61, 30, 61, 122, 142, 91, 91, 183, 244, 244];
aliases[10] = [0, 0, 0, 0, 8, 8, 0, 9, 6, 8, 9, 9];
// Dog/Clothes
rarities[11] = [254, 107, 107, 35, 152, 198, 35, 107, 117, 132, 107, 107, 107, 107];
aliases[11] = [0, 4, 5, 5, 0, 4, 5, 5, 5, 8, 8, 8, 9, 9];
// Dog/Tail
rarities[12] = [140, 254, 84, 84, 84, 203, 140, 196, 196, 140, 140];
aliases[12] = [1, 0, 5, 5, 5, 1, 5, 5, 5, 5, 5];
// Dog/alphaIndex
rarities[13] = [254, 101, 153, 51];
aliases[13] = [0, 0, 0, 1];
}
modifier requireContractsSet() {
require(
address(traits) != address(0) && address(staking) != address(0),
"Contracts not set"
);
_;
}
function setContracts(ITraits _traits, IStaking _staking, IDIAMOND _diamond)
external
onlyOwner
{
traits = _traits;
staking = _staking;
diamond = _diamond;
}
function setWhiteListMerkleRoot(bytes32 _root) external onlyOwner {
whitelistMerkleRoot = _root;
}
modifier isValidMerkleProof(bytes32[] memory proof) {
require(
MerkleProof.verify(
proof,
whitelistMerkleRoot,
bytes32(uint256(uint160(_msgSender())))
),
"INVALID_MERKLE_PROOF"
);
_;
}
/** EXTERNAL */
/**
* Returns the total amount of tokens minted in the contract.
*/
function minted() external view returns (uint256) {
return _totalMinted();
}
function communitySaleLeft(bytes32[] memory merkleProof)
external
view
isValidMerkleProof(merkleProof)
returns (uint256)
{
if (_totalMinted() >= PAID_TOKENS) return 0;
return MAX_COMMUNITY_AMOUNT - claimed[_msgSender()];
}
/**
* mint a token - 90% Llama, 10% Dog
* The first 20% are free to claim, the remaining cost $DIAMOND
*/
function mintGame(uint256 amount, bool stake)
internal
whenNotPaused
nonReentrant
returns (uint16[] memory tokenIds)
{
require(tx.origin == _msgSender(), "ONLY_EOA");
require(_totalMinted() + amount <= MAX_TOKENS, "MINT_ENDED");
require(amount > 0 && amount <= 15, "MINT_AMOUNT_INVALID");
uint256 totalDiamondCost = 0;
tokenIds = new uint16[](amount);
uint16 token = uint16(_totalMinted());
for (uint256 i = 0; i < amount; i++) {
token++;
generate(token, random(token));
tokenIds[i] = token;
totalDiamondCost += mintCost(token);
}
if (totalDiamondCost > 0) diamond.burn(_msgSender(), totalDiamondCost);
_mint(stake ? address(staking) : _msgSender(), amount, "", false);
if (stake) staking.addManyToStaking(_msgSender(), tokenIds);
return tokenIds;
}
/**
* mint a token - 90% Llama, 10% Dog
* The first 20% are free to claim, the remaining cost $DIAMOND
*/
function mint(uint256 amount, bool stake) external payable {
if (_totalMinted() < PAID_TOKENS) {
// we have to still pay in ETH, we can make a transaction that pays both in ETH and DIAMOND
// check how many tokens should be paid in ETH, the DIAMOND will be burned in mintGame function
require(msg.value == (amount > (PAID_TOKENS - _totalMinted()) ? (PAID_TOKENS - _totalMinted()) : amount) * MINT_PRICE, "MINT_PAID_PRICE_INVALID");
} else {
require(msg.value == 0, "MINT_PAID_IN_DIAMONDS");
}
mintGame(amount, stake);
}
function mintCommunitySale(
bytes32[] memory merkleProof,
uint256 amount,
bool stake
) external payable isValidMerkleProof(merkleProof) {
require(
claimed[_msgSender()] + amount <= MAX_COMMUNITY_AMOUNT,
"MINT_COMMUNITY_ENDED"
);
require(_totalMinted() + amount <= PAID_TOKENS, "MINT_ENDED");
require(msg.value == COMMUNITY_SALE_MINT_PRICE * (claimed[_msgSender()] == 0 ? amount - 1 : amount), "MINT_COMMUNITY_PRICE_INVALID");
claimed[_msgSender()] += amount;
mintGame(amount, stake);
}
/**
* 0 - 20% = eth
* 20 - 40% = 200 DIAMONDS
* 40 - 60% = 300 DIAMONDS
* 60 - 80% = 400 DIAMONDS
* 80 - 100% = 500 DIAMONDS
* @param tokenId the ID to check the cost of to mint
* @return the cost of the given token ID
*/
function mintCost(uint256 tokenId) public view returns (uint256) {
if (tokenId <= PAID_TOKENS) return 0; // 1 / 5 = PAID_TOKENS
if (tokenId <= (MAX_TOKENS * 2) / 5) return 200 ether;
if (tokenId <= (MAX_TOKENS * 3) / 5) return 300 ether;
if (tokenId <= (MAX_TOKENS * 4) / 5) return 400 ether;
return 500 ether;
}
function isApprovedForAll(address owner, address operator) public view override(ERC721AUpgradeable, IERC721Upgradeable) returns (bool) {
return (address(staking) == operator || ERC721AUpgradeable.isApprovedForAll(owner, operator));
}
/** INTERNAL */
/**
* generates traits for a specific token, checking to make sure it's unique
* @param tokenId the id of the token to generate traits for
* @param seed a pseudorandom 256 bit number to derive traits from
* @return t - a struct of traits for the given token ID
*/
function generate(uint256 tokenId, uint256 seed)
internal
returns (LlamaDog memory t)
{
t = selectTraits(tokenId, seed);
if (existingCombinations[structToHash(t)] == 0) {
tokenTraits[tokenId] = t;
existingCombinations[structToHash(t)] = tokenId;
if (t.isLlama) {
emit LlamaMinted(tokenId);
} else {
emit DogMinted(tokenId);
}
return t;
}
return generate(tokenId, random(seed));
}
/**
* uses A.J. Walker's Alias algorithm for O(1) rarity table lookup
* ensuring O(1) instead of O(n) reduces mint cost by more than 50%
* probability & alias tables are generated off-chain beforehand
* @param seed portion of the 256 bit seed to remove trait correlation
* @param traitType the trait type to select a trait for
* @return the ID of the randomly selected trait
*/
function selectTrait(uint16 seed, uint8 traitType)
internal
view
returns (uint8)
{
uint8 trait = uint8(seed) % uint8(rarities[traitType].length);
// If a selected random trait probability is selected (biased coin) return that trait
if (seed >> 8 <= rarities[traitType][trait]) return trait;
return aliases[traitType][trait];
}
/**
* selects the species and all of its traits based on the seed value
* @param seed a pseudorandom 256 bit number to derive traits from
* @return t - a struct of randomly selected traits
*/
function selectTraits(uint256 tokenId, uint256 seed)
internal
view
returns (LlamaDog memory t)
{
// if tokenId < PAID_TOKENS, 2 in 10 chance of a dog, otherwise 1 in 10 chance of a dog
t.isLlama = tokenId < PAID_TOKENS ? (seed & 0xFFFF) % 10 < 9 : (seed & 0xFFFF) % 10 < 1;
uint8 shift = t.isLlama ? 0 : 7;
// what happens here is that we check the 16 least signficial bits of the seed
// and then remove them from the seed, so that the next 16 bits are used for the next trait
// Before: EBD302F8B72AB0883F98D59C3BB7C25C61E30A77AB5F93924D234A620A32
// After: EBD302F8B72AB0883F98D59C3BB7C25C61E30A77AB5F93924D234A62
// trait 1: 0A32 -> 00001010 00110010
seed >>= 16;
t.body = selectTrait(uint16(seed & 0xFFFF), 0 + shift);
seed >>= 16;
t.hat = selectTrait(uint16(seed & 0xFFFF), 1 + shift);
seed >>= 16;
t.eye = selectTrait(uint16(seed & 0xFFFF), 2 + shift);
seed >>= 16;
t.mouth = selectTrait(uint16(seed & 0xFFFF), 3 + shift);
seed >>= 16;
t.clothes = selectTrait(uint16(seed & 0xFFFF), 4 + shift);
seed >>= 16;
t.tail = selectTrait(uint16(seed & 0xFFFF), 5 + shift);
seed >>= 16;
t.alphaIndex = selectTrait(uint16(seed & 0xFFFF), 6 + shift);
}
/**
* converts a struct to a 256 bit hash to check for uniqueness
* @param s the struct to pack into a hash
* @return the 256 bit hash of the struct
*/
function structToHash(LlamaDog memory s) internal pure returns (uint256) {
return
uint256(
bytes32(
abi.encodePacked(
s.isLlama,
s.body,
s.hat,
s.eye,
s.mouth,
s.clothes,
s.tail,
s.alphaIndex
)
)
);
}
/**
* generates a pseudorandom number
* @param seed a value ensure different outcomes for different sources in the same block
* @return a pseudorandom value
*/
function random(uint256 seed) internal view returns (uint256) {
return
uint256(
keccak256(
abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
)
)
);
}
/** READ */
function getTokenTraits(uint256 tokenId)
external
view
override
returns (LlamaDog memory)
{
require(
_exists(tokenId),
"ERC721Metadata: token traits query for nonexistent token"
);
return tokenTraits[tokenId];
}
function getPaidTokens() external view override returns (uint256) {
return PAID_TOKENS;
}
/**
* checks if a token is a Wizards
* @param tokenId the ID of the token to check
* @return wizard - whether or not a token is a Wizards
*/
function isLlama(uint256 tokenId)
external
view
override
returns (bool)
{
IDiamondHeist.LlamaDog memory s = tokenTraits[tokenId];
return s.isLlama;
}
/** ADMIN */
/**
* allows owner to withdraw funds from minting
*/
function withdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
/**
* updates the number of tokens for sale
*/
function setPaidTokens(uint256 _paidTokens) external onlyOwner {
PAID_TOKENS = _paidTokens;
}
/**
* updates the mint price
*/
function setMintPrice(uint256 _mintPrice) external onlyOwner {
MINT_PRICE = _mintPrice;
COMMUNITY_SALE_MINT_PRICE = _mintPrice / 4 * 3;
}
/**
* enables owner to pause / unpause minting
*/
function setPaused(bool _paused) external requireContractsSet onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** RENDER */
function tokenURI(uint256 tokenId)
public
view
override(ERC721AUpgradeable, IERC721MetadataUpgradeable)
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
return traits.tokenURI(tokenId);
}
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// 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/token/ERC721/[email protected]
// 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/security/[email protected]
// 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/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File contracts/Staking.sol
pragma solidity ^0.8.0;
contract Staking is IStaking, Ownable, ReentrancyGuard, IERC721Receiver, Pausable {
// maximum alpha score for a Dog
uint8 public constant MAX_ALPHA = 8;
// struct to store a stake's token, owner, and earning values
struct Stake {
uint16 tokenId;
uint80 value;
address owner;
}
uint256 private totalAlphaStaked;
uint256 public numLlamaStaked;
event TokenStaked(address indexed owner, uint256 indexed tokenId, bool indexed isLlama, uint256 value);
event LlamaClaimed(uint256 indexed tokenId, bool indexed unstaked, uint256 earned);
event DogClaimed(uint256 indexed tokenId, bool indexed unstaked, uint256 earned);
// reference to the DiamondHeist NFT contract
IDiamondHeist public game;
// reference to the $DIAMOND contract for minting $DIAMOND earnings
IDIAMOND public diamond;
// maps tokenId to stake for llamas
mapping(uint256 => Stake) public staking;
// maps alpha to all Dog stakes with that alpha
mapping(uint256 => Stake[]) public dogStaking;
// tracks location of each Dog in Staking
mapping(uint256 => uint256) public dogIndices;
// any rewards distributed when no dogs are staked
uint256 public unaccountedRewards = 0;
// amount of $DIAMOND due for each alpha point staked
uint256 public diamondPerAlpha = 0;
// llama earn 100 $DIAMOND per day
uint256 public constant DAILY_DIAMOND_RATE = 100 ether;
// llamas must have 2 days worth of $DIAMOND to unstake or else they're still staked
uint256 public constant MINIMUM_TO_EXIT = 2 days;
// dogs take a 20% tax on all $DIAMOND claimed
uint256 public constant DIAMOND_CLAIM_TAX_PERCENTAGE = 20;
// there will only ever be (roughly) 24 million $DIAMOND earned through staking
uint256 public constant MAXIMUM_GLOBAL_DIAMOND = 24000000 ether;
// amount of $DIAMOND earned so far
uint256 public totalDiamondEarned;
// the last time $DIAMOND was claimed
uint256 public lastClaimTimestamp;
// emergency rescue to allow unstaking without any checks but without $DIAMOND
bool public rescueEnabled = false;
modifier onlyDuringDay {
require((block.timestamp % (6*3600)) > (3*3600), "ONLY DURING DAY");
_;
}
constructor() {
_pause();
}
modifier requireContractsSet() {
require(address(game) != address(0) && address(diamond) != address(0), "CONTRACTS NOT SET");
_;
}
function setContracts(IDiamondHeist _diamondheist, IDIAMOND _diamond) external onlyOwner {
game = _diamondheist;
diamond = _diamond;
}
/** STAKING */
/**
* Stakes Llamas and Dogs
* @param account the address of the staker
* @param tokenIds the IDs of the Llamas and Dogs to stake
*/
function addManyToStaking(address account, uint16[] calldata tokenIds) external override whenNotPaused nonReentrant {
require(tx.origin == _msgSender() || _msgSender() == address(game), "Only EOA");
require(account == tx.origin, "account to sender mismatch");
for (uint i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] == 0) {
continue;
}
if (_msgSender() != address(game)) { // dont do this step if its a mint + stake
require(game.ownerOf(tokenIds[i]) == _msgSender(), "You don't own this token");
game.transferFrom(_msgSender(), address(this), tokenIds[i]);
}
if (game.isLlama(tokenIds[i]))
_addLlama(account, tokenIds[i]);
else
_addDog(account, tokenIds[i]);
}
}
/**
* adds a single Llamas to the Staking
* @param account the address of the staker
* @param tokenId the ID of the Llamas to add to the Staking
*/
function _addLlama(address account, uint256 tokenId) internal whenNotPaused _updateEarnings {
staking[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
});
numLlamaStaked += 1;
emit TokenStaked(account, tokenId, true, block.timestamp);
}
/**
* Stake a Dog
* @param account the address of the staker
* @param tokenId the ID of the Dog to add to Staking
*/
function _addDog(address account, uint256 tokenId) internal {
uint256 alpha = _alphaForDog(tokenId);
totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5
dogIndices[tokenId] = dogStaking[alpha].length; // Store the location of the dog in the Staking
dogStaking[alpha].push(Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(diamondPerAlpha)
})); // Add the dog to the Staking
emit TokenStaked(account, tokenId, false, diamondPerAlpha);
}
/** CLAIMING / UNSTAKING */
/**
* realize $DIAMOND earnings and optionally unstake tokens from the Staking / Staking
* to unstake a Llamas it will require it has 2 days worth of $DIAMOND unclaimed
* @param tokenIds the IDs of the tokens to claim earnings from
* @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
*/
function claimMany(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings onlyDuringDay nonReentrant {
require(tx.origin == _msgSender() || _msgSender() == address(game), "Only EOA");
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
if (game.isLlama(tokenIds[i]))
owed += _claimLlama(tokenIds[i], unstake);
else
owed += _claimDog(tokenIds[i], unstake);
}
if (owed == 0) return;
diamond.mint(_msgSender(), owed);
}
/**
* realize $DIAMOND earnings for a single Llamas and optionally unstake it
* if not unstaking, pay a 20% tax to the staked Dogs
* if unstaking, there is a 50% chance all $DIAMOND is stolen
* @param tokenId the ID of the Llamas to claim earnings from
* @param unstake whether or not to unstake the Llamas
* @return owed - the amount of $DIAMOND earned
*/
function _claimLlama(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake memory stake = staking[tokenId];
require(stake.owner == _msgSender(), "Don't own the given token");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "Wait 2 days to unstake");
if (totalDiamondEarned < MAXIMUM_GLOBAL_DIAMOND) {
owed = (block.timestamp - stake.value) * DAILY_DIAMOND_RATE / 1 days;
} else if (stake.value > lastClaimTimestamp) {
// $DIAMOND production stopped already
owed = 0;
} else {
// stop earning additional $DIAMOND if it's all been earned
owed = (lastClaimTimestamp - stake.value) * DAILY_DIAMOND_RATE / 1 days;
}
if (unstake) {
if (random(tokenId) & 1 == 1) { // 50% chance of all $DIAMOND stolen
_payDogTax(owed);
owed = 0;
}
delete staking[tokenId];
numLlamaStaked -= 1;
// Always transfer last to guard against reentrance
game.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Llamas
} else {
_payDogTax(owed * DIAMOND_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked dogs
owed = owed * (100 - DIAMOND_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Llamas owner
staking[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}); // reset stake
}
emit LlamaClaimed(tokenId, unstake, owed);
}
/**
* realize $DIAMOND earnings for a single Dog and optionally unstake it
* Dogs earn $DIAMOND proportional to their Alpha rank
* @param tokenId the ID of the Dog to claim earnings from
* @param unstake whether or not to unstake the Dog
* @return owed - the amount of $DIAMOND earned
*/
function _claimDog(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(game.ownerOf(tokenId) == address(this), "Not staked");
uint256 alpha = _alphaForDog(tokenId);
Stake memory stake = dogStaking[alpha][dogIndices[tokenId]];
require(stake.owner == _msgSender(), "Doesn't own token");
owed = (alpha) * (diamondPerAlpha - stake.value); // Calculate portion of tokens based on Alpha
if (unstake) {
totalAlphaStaked -= alpha; // Remove Alpha from total staked
Stake memory lastStake = dogStaking[alpha][dogStaking[alpha].length - 1];
dogStaking[alpha][dogIndices[tokenId]] = lastStake; // Shuffle last Dog to current position
dogIndices[lastStake.tokenId] = dogIndices[tokenId];
dogStaking[alpha].pop(); // Remove duplicate
delete dogIndices[tokenId]; // Delete old mapping
// Always remove last to guard against reentrance
game.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Dog
} else {
dogStaking[alpha][dogIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(diamondPerAlpha)
}); // reset stake
}
emit DogClaimed(tokenId, unstake, owed);
}
/**
* emergency unstake tokens
* @param tokenIds the IDs of the tokens to claim earnings from
*/
function rescue(uint256[] calldata tokenIds) external nonReentrant {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (game.isLlama(tokenId)) {
stake = staking[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete staking[tokenId];
numLlamaStaked -= 1;
game.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Llamas
emit LlamaClaimed(tokenId, true, 0);
} else {
alpha = _alphaForDog(tokenId);
stake = dogStaking[alpha][dogIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
totalAlphaStaked -= alpha; // Remove Alpha from total staked
lastStake = dogStaking[alpha][dogStaking[alpha].length - 1];
dogStaking[alpha][dogIndices[tokenId]] = lastStake; // Shuffle last Dog to current position
dogIndices[lastStake.tokenId] = dogIndices[tokenId];
dogStaking[alpha].pop(); // Remove duplicate
delete dogIndices[tokenId]; // Delete old mapping
game.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Dog
emit DogClaimed(tokenId, true, 0);
}
}
}
/**
* add $DIAMOND to claimable pot for the Staking
* @param amount $DIAMOND to add to the pot
*/
function _payDogTax(uint256 amount) internal {
if (totalAlphaStaked == 0) { // if there's no staked dogs
unaccountedRewards += amount; // keep track of $DIAMOND due to dogs
return;
}
// makes sure to include any unaccounted $DIAMOND
diamondPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked;
unaccountedRewards = 0;
}
/**
* tracks $DIAMOND earnings to ensure it stops once 2.4 billion is eclipsed
*/
modifier _updateEarnings() {
if (totalDiamondEarned < MAXIMUM_GLOBAL_DIAMOND) {
totalDiamondEarned +=
(block.timestamp - lastClaimTimestamp)
* numLlamaStaked
* DAILY_DIAMOND_RATE / 1 days;
lastClaimTimestamp = block.timestamp;
}
_;
}
/** ADMIN */
/**
* allows owner to enable "rescue mode"
* simplifies accounting, prioritizes tokens out in emergency
*/
function setRescueEnabled(bool _enabled) external onlyOwner {
rescueEnabled = _enabled;
}
/**
* enables owner to pause / unpause contract
*/
function setPaused(bool _paused) external requireContractsSet onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** READ ONLY */
/**
* gets the alpha score for a Dog
* @param tokenId the ID of the Dog to get the alpha score for
* @return the alpha score of the Dog (5-8)
*/
function _alphaForDog(uint256 tokenId) internal view returns (uint8) {
IDiamondHeist.LlamaDog memory s = game.getTokenTraits(tokenId);
return MAX_ALPHA - s.alphaIndex; // alpha index is 0-3
}
/**
* generates a pseudorandom number
* @param seed a value ensure different outcomes for different sources in the same block
* @return a pseudorandom value
*/
function random(uint256 seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
)));
}
function onERC721Received(
address,
address from,
uint256,
bytes calldata
) external pure override returns (bytes4) {
require(from == address(0x0), "Cannot send tokens to Staking directly");
return IERC721Receiver.onERC721Received.selector;
}
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File contracts/Traits.sol
pragma solidity ^0.8.0;
contract Traits is Ownable, ITraits {
using Strings for uint256;
// struct to store each trait's data for metadata and rendering
struct Trait {
string name;
string png;
}
// mapping from trait type (index) to its name
string[9] _traitTypes = [
"Body",
"Hat",
"Eye",
"Mouth",
"Clothes",
"Tail",
"Alpha"
];
// storage of each traits name and base64 PNG data
mapping(uint8 => mapping(uint8 => Trait)) public traitData;
// mapping from alphaIndex to its score
string[4] _alphas = [
"8",
"7",
"6",
"5"
];
IDiamondHeist public diamondheist;
string private llamaDescription;
string private dogDescription;
constructor() {}
/** ADMIN */
function setGame(address _diamondheist) external onlyOwner {
diamondheist = IDiamondHeist(_diamondheist);
}
/**
* administrative to upload the names and images associated with each trait
* @param traitType the trait type to upload the traits for (see traitTypes for a mapping)
* @param traits the names and base64 encoded PNGs for each trait
*/
function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner {
require(traitIds.length == traits.length, "Mismatched inputs");
for (uint i = 0; i < traits.length; i++) {
traitData[traitType][traitIds[i]] = Trait(
traits[i].name,
traits[i].png
);
}
}
/** RENDER */
/**
* generates an <image> element using base64 encoded PNGs
* @param trait the trait storing the PNG data
* @return the <image> element
*/
function drawTrait(Trait memory trait) internal pure returns (string memory) {
return string(abi.encodePacked(
'<image x="4" y="4" width="32" height="32" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="data:image/png;base64,',
trait.png,
'"/>'
));
}
/**
* generates an entire SVG by composing multiple <image> elements of PNGs
* @param tokenId the ID of the token to generate an SVG for
* @return a valid SVG of the Llama / Dog
*/
function drawSVG(uint256 tokenId) public view returns (string memory) {
IDiamondHeist.LlamaDog memory s = diamondheist.getTokenTraits(tokenId);
uint8 shift = s.isLlama ? 0 : 7;
string memory svgString = string(abi.encodePacked(
drawTrait(traitData[0 + shift][s.body]),
drawTrait(traitData[1 + shift][s.hat]),
drawTrait(traitData[2 + shift][s.eye]),
drawTrait(traitData[3 + shift][s.mouth]),
drawTrait(traitData[4 + shift][s.clothes]),
drawTrait(traitData[5 + shift][s.tail])
));
return string(abi.encodePacked(
'<svg id="diamondheist" width="100%" height="100%" version="1.1" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">',
svgString,
"</svg>"
));
}
/**
* generates an attribute for the attributes array in the ERC721 metadata standard
* @param traitType the trait type to reference as the metadata key
* @param value the token's trait associated with the key
* @return a JSON dictionary for the single attribute
*/
function attributeForTypeAndValue(string memory traitType, string memory value) internal pure returns (string memory) {
return string(abi.encodePacked(
'{"trait_type":"',
traitType,
'","value":"',
value,
'"}'
));
}
/**
* generates an attribute for the attributes array in the ERC721 metadata standard
* @param traitType the trait type to reference as the metadata key
* @param value the token's trait associated with the key
* @return a JSON dictionary for the single attribute
*/
function attributeForTypeAndValueNumber(string memory traitType, string memory value) internal pure returns (string memory) {
return string(abi.encodePacked(
'{"display_type": "number", "trait_type":"',
traitType,
'","value":"',
value,
'"}'
));
}
/**
* generates an array composed of all the individual traits and values
* @param tokenId the ID of the token to compose the metadata for
* @return a JSON array of all of the attributes for given token ID
*/
function compileAttributes(uint256 tokenId) public view returns (string memory) {
IDiamondHeist.LlamaDog memory s = diamondheist.getTokenTraits(tokenId);
string memory traits;
if (s.isLlama) {
traits = string(abi.encodePacked(
attributeForTypeAndValue(_traitTypes[0], traitData[0][s.body].name),",",
attributeForTypeAndValue(_traitTypes[1], traitData[1][s.hat].name),",",
attributeForTypeAndValue(_traitTypes[2], traitData[2][s.eye].name),",",
attributeForTypeAndValue(_traitTypes[3], traitData[3][s.mouth].name),",",
attributeForTypeAndValue(_traitTypes[4], traitData[4][s.clothes].name),",",
attributeForTypeAndValue(_traitTypes[5], traitData[5][s.tail].name),","
// traitData 6 = alpha score, but not visible
));
} else {
traits = string(abi.encodePacked(
attributeForTypeAndValue(_traitTypes[0], traitData[7][s.body].name),",",
attributeForTypeAndValue(_traitTypes[1], traitData[8][s.hat].name),",",
attributeForTypeAndValue(_traitTypes[2], traitData[9][s.eye].name),",",
attributeForTypeAndValue(_traitTypes[3], traitData[10][s.mouth].name),",",
attributeForTypeAndValue(_traitTypes[4], traitData[11][s.clothes].name),",",
attributeForTypeAndValue(_traitTypes[5], traitData[12][s.tail].name),",",
attributeForTypeAndValueNumber("Alpha Score", _alphas[s.alphaIndex]),","
));
}
return string(abi.encodePacked(
'[',
traits,
'{"trait_type":"Generation","value":',
tokenId <= diamondheist.getPaidTokens() ? '"Gen 0"' : '"Gen 1"',
'},{"trait_type":"Type","value":',
s.isLlama ? '"Llama"' : '"Dog"',
'}]'
));
}
/**
* generates a base64 encoded metadata response without referencing off-chain content
* @param tokenId the ID of the token to generate the metadata for
* @return a base64 encoded JSON dictionary of the token's metadata and SVG
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
IDiamondHeist.LlamaDog memory s = diamondheist.getTokenTraits(tokenId);
string memory metadata = string(abi.encodePacked(
'{"name": "',
s.isLlama ? 'Llama #' : 'Dog #',
tokenId.toString(),
'", "description": "',
s.isLlama ? llamaDescription : dogDescription,
'", "image": "data:image/svg+xml;base64,',
base64(bytes(drawSVG(tokenId))),
'", "attributes":',
compileAttributes(tokenId),
"}"
));
return string(abi.encodePacked(
"data:application/json;base64,",
base64(bytes(metadata))
));
}
function setDescription(string memory _llama, string memory _dog) external onlyOwner {
llamaDescription = _llama;
dogDescription = _dog;
}
/** BASE 64 - Written by Brech Devos */
string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function base64(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
} | * generates an array composed of all the individual traits and values @param tokenId the ID of the token to compose the metadata for @return a JSON array of all of the attributes for given token ID/ traitData 6 = alpha score, but not visible | function compileAttributes(uint256 tokenId) public view returns (string memory) {
IDiamondHeist.LlamaDog memory s = diamondheist.getTokenTraits(tokenId);
string memory traits;
if (s.isLlama) {
traits = string(abi.encodePacked(
attributeForTypeAndValue(_traitTypes[0], traitData[0][s.body].name),",",
attributeForTypeAndValue(_traitTypes[1], traitData[1][s.hat].name),",",
attributeForTypeAndValue(_traitTypes[2], traitData[2][s.eye].name),",",
attributeForTypeAndValue(_traitTypes[3], traitData[3][s.mouth].name),",",
attributeForTypeAndValue(_traitTypes[4], traitData[4][s.clothes].name),",",
attributeForTypeAndValue(_traitTypes[5], traitData[5][s.tail].name),","
));
traits = string(abi.encodePacked(
attributeForTypeAndValue(_traitTypes[0], traitData[7][s.body].name),",",
attributeForTypeAndValue(_traitTypes[1], traitData[8][s.hat].name),",",
attributeForTypeAndValue(_traitTypes[2], traitData[9][s.eye].name),",",
attributeForTypeAndValue(_traitTypes[3], traitData[10][s.mouth].name),",",
attributeForTypeAndValue(_traitTypes[4], traitData[11][s.clothes].name),",",
attributeForTypeAndValue(_traitTypes[5], traitData[12][s.tail].name),",",
attributeForTypeAndValueNumber("Alpha Score", _alphas[s.alphaIndex]),","
));
}
return string(abi.encodePacked(
'[',
traits,
'{"trait_type":"Generation","value":',
tokenId <= diamondheist.getPaidTokens() ? '"Gen 0"' : '"Gen 1"',
s.isLlama ? '"Llama"' : '"Dog"',
'}]'
));
}
| 14,374,569 | [
1,
3441,
815,
392,
526,
18673,
434,
777,
326,
7327,
18370,
471,
924,
225,
1147,
548,
326,
1599,
434,
326,
1147,
358,
11458,
326,
1982,
364,
327,
279,
1796,
526,
434,
777,
434,
326,
1677,
364,
864,
1147,
1599,
19,
13517,
751,
1666,
273,
4190,
4462,
16,
1496,
486,
6021,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
4074,
2498,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
565,
1599,
29401,
1434,
5256,
376,
18,
48,
80,
20789,
40,
717,
3778,
272,
273,
4314,
301,
1434,
580,
376,
18,
588,
1345,
30370,
12,
2316,
548,
1769,
203,
565,
533,
3778,
18370,
31,
203,
565,
309,
261,
87,
18,
291,
48,
80,
20789,
13,
288,
203,
1377,
18370,
273,
533,
12,
21457,
18,
3015,
4420,
329,
12,
203,
3639,
1566,
22405,
30154,
24899,
22513,
2016,
63,
20,
6487,
13517,
751,
63,
20,
6362,
87,
18,
3432,
8009,
529,
3631,
3113,
3113,
203,
3639,
1566,
22405,
30154,
24899,
22513,
2016,
63,
21,
6487,
13517,
751,
63,
21,
6362,
87,
18,
11304,
8009,
529,
3631,
3113,
3113,
203,
3639,
1566,
22405,
30154,
24899,
22513,
2016,
63,
22,
6487,
13517,
751,
63,
22,
6362,
87,
18,
402,
73,
8009,
529,
3631,
3113,
3113,
203,
3639,
1566,
22405,
30154,
24899,
22513,
2016,
63,
23,
6487,
13517,
751,
63,
23,
6362,
87,
18,
81,
15347,
8009,
529,
3631,
3113,
3113,
203,
3639,
1566,
22405,
30154,
24899,
22513,
2016,
63,
24,
6487,
13517,
751,
63,
24,
6362,
87,
18,
830,
10370,
281,
8009,
529,
3631,
3113,
3113,
203,
3639,
1566,
22405,
30154,
24899,
22513,
2016,
63,
25,
6487,
13517,
751,
63,
25,
6362,
87,
18,
13101,
8009,
529,
3631,
15937,
203,
1377,
262,
1769,
203,
1377,
18370,
273,
533,
12,
21457,
18,
3015,
4420,
329,
12,
203,
3639,
1566,
22405,
30154,
24899,
22513,
2016,
63,
20,
6487,
13517,
751,
63,
2
] |
./full_match/1/0x877C7ae9D03A4b0daA55eC74Eb6409853b1cfbA1/sources/browser/TorroCollab.sol | @notice Decreases allowance for given spender. @param spender_ spender to decrease allowance for. @param subtractedValue_ removed amount that spender can spend. @return bool true if successful. | function decreaseAllowance(address spender_, uint256 subtractedValue_) public returns (bool) {
return false;
}
| 3,154,286 | [
1,
23326,
3304,
1699,
1359,
364,
864,
17571,
264,
18,
225,
17571,
264,
67,
17571,
264,
358,
20467,
1699,
1359,
364,
18,
225,
10418,
329,
620,
67,
3723,
3844,
716,
17571,
264,
848,
17571,
18,
327,
1426,
638,
309,
6873,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
67,
16,
2254,
5034,
10418,
329,
620,
67,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
327,
629,
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
] |
./partial_match/1/0xd6F2E30B99214B6eaffBE2B270d2e42c762a929B/sources/DisputeManager.sol | * @notice Draft jurors for the next round of dispute #`_disputeId` @param _disputeId Identification number of the dispute to be drafted/ Drafts can only be computed when the Court is up-to-date. Note that forcing a term transition won't work since the term randomness is always based on the next term which means it won't be available anyway. Ensure dispute has not been drafted yet Ensure draft term randomness can be computed for the current block number Draft jurors for the given dispute and reimburse fees If the drafting is over, update its state No need for SafeMath: we ensured `currentTermId` is greater than or equal to `draftTermId` above | function draft(uint256 _disputeId) external disputeExists(_disputeId) {
IClock clock = _clock();
uint64 requiredTransitions = _clock().getNeededTermTransitions();
require(uint256(requiredTransitions) == 0, ERROR_TERM_OUTDATED);
uint64 currentTermId = _getLastEnsuredTermId();
Dispute storage dispute = disputes[_disputeId];
require(dispute.state == DisputeState.PreDraft, ERROR_ROUND_ALREADY_DRAFTED);
AdjudicationRound storage round = dispute.rounds[dispute.rounds.length - 1];
uint64 draftTermId = round.draftTermId;
require(draftTermId <= currentTermId, ERROR_DRAFT_TERM_NOT_REACHED);
bytes32 draftTermRandomness = clock.ensureCurrentTermRandomness();
DraftConfig memory config = _getDraftConfig(draftTermId);
bool draftEnded = _draft(_disputeId, round, currentTermId, draftTermRandomness, config);
if (draftEnded) {
round.delayedTerms = currentTermId - draftTermId;
dispute.state = DisputeState.Adjudicating;
emit DisputeStateChanged(_disputeId, DisputeState.Adjudicating);
}
}
| 4,343,446 | [
1,
12714,
525,
295,
1383,
364,
326,
1024,
3643,
434,
1015,
2507,
1375,
67,
2251,
2507,
548,
68,
225,
389,
2251,
2507,
548,
13128,
1480,
1300,
434,
326,
1015,
2507,
358,
506,
12246,
329,
19,
463,
5015,
87,
848,
1338,
506,
8470,
1347,
326,
385,
477,
88,
353,
731,
17,
869,
17,
712,
18,
3609,
716,
364,
2822,
279,
2481,
6007,
8462,
1404,
1440,
3241,
326,
2481,
2744,
4496,
353,
3712,
2511,
603,
326,
1024,
2481,
1492,
4696,
518,
8462,
1404,
506,
2319,
13466,
18,
7693,
1015,
2507,
711,
486,
2118,
12246,
329,
4671,
7693,
12246,
2481,
2744,
4496,
848,
506,
8470,
364,
326,
783,
1203,
1300,
463,
5015,
525,
295,
1383,
364,
326,
864,
1015,
2507,
471,
283,
381,
70,
295,
307,
1656,
281,
971,
326,
12246,
310,
353,
1879,
16,
1089,
2097,
919,
2631,
1608,
364,
14060,
10477,
30,
732,
3387,
72,
1375,
2972,
4065,
548,
68,
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,
565,
445,
12246,
12,
11890,
5034,
389,
2251,
2507,
548,
13,
3903,
1015,
2507,
4002,
24899,
2251,
2507,
548,
13,
288,
203,
3639,
467,
14027,
7268,
273,
389,
18517,
5621,
203,
3639,
2254,
1105,
1931,
23299,
273,
389,
18517,
7675,
588,
11449,
4065,
23299,
5621,
203,
3639,
2583,
12,
11890,
5034,
12,
4718,
23299,
13,
422,
374,
16,
5475,
67,
15176,
67,
5069,
4594,
40,
1769,
203,
3639,
2254,
1105,
783,
4065,
548,
273,
389,
588,
3024,
12512,
72,
4065,
548,
5621,
203,
203,
3639,
3035,
2507,
2502,
1015,
2507,
273,
1015,
458,
281,
63,
67,
2251,
2507,
548,
15533,
203,
3639,
2583,
12,
2251,
2507,
18,
2019,
422,
3035,
2507,
1119,
18,
1386,
12714,
16,
5475,
67,
15092,
67,
1013,
20305,
67,
28446,
42,
6404,
1769,
203,
203,
3639,
4052,
78,
1100,
829,
11066,
2502,
3643,
273,
1015,
2507,
18,
27950,
63,
2251,
2507,
18,
27950,
18,
2469,
300,
404,
15533,
203,
3639,
2254,
1105,
12246,
4065,
548,
273,
3643,
18,
17153,
4065,
548,
31,
203,
3639,
2583,
12,
17153,
4065,
548,
1648,
783,
4065,
548,
16,
5475,
67,
28446,
4464,
67,
15176,
67,
4400,
67,
29416,
15023,
1769,
203,
3639,
1731,
1578,
12246,
4065,
8529,
4496,
273,
7268,
18,
15735,
3935,
4065,
8529,
4496,
5621,
203,
203,
3639,
463,
5015,
809,
3778,
642,
273,
389,
588,
12714,
809,
12,
17153,
4065,
548,
1769,
203,
3639,
1426,
12246,
28362,
273,
389,
17153,
24899,
2251,
2507,
548,
16,
3643,
16,
783,
4065,
548,
16,
12246,
4065,
8529,
4496,
16,
642,
1769,
203,
203,
3639,
2
] |
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol | @dev Reads the uint32 at `cdPtr` in calldata. | function readUint32(
CalldataPointer cdPtr
) internal pure returns (uint32 value) {
assembly {
value := calldataload(cdPtr)
}
}
| 4,300,218 | [
1,
7483,
326,
2254,
1578,
622,
1375,
4315,
5263,
68,
316,
745,
892,
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
] | [
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,
855,
5487,
1578,
12,
203,
3639,
3049,
892,
4926,
7976,
5263,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
1578,
460,
13,
288,
203,
3639,
19931,
288,
203,
5411,
460,
519,
745,
72,
3145,
6189,
12,
4315,
5263,
13,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.19;
contract mortal {
/* Define variable owner of the type address. This is effectively the
government agency responsible for registering the property. */
address owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/* this function is executed at initialization and sets the owner of the contract */
function mortal() public { owner = msg.sender; }
/* Function to recover the funds on the contract */
function kill() public onlyOwner { if (msg.sender == owner) selfdestruct(owner); }
}
contract PropertyRegistry is mortal {
/* Possible states for the contract */
enum State { OWNED, SALE_INITIATED, CALCULATING_TAXES, WAITING_FINALIZATION }
struct PropertyAddress {
string registrationNumber;
string streetAddress;
string city;
string province;
}
struct ProspectiveSale {
address buyer;
// Solidity still doesn't fully support floating point numbers,
// so this is stored in CAD$ times 100
uint256 salePrice;
uint256 exchangeRate;
}
struct ProspectiveBuyer {
string name;
uint age;
bool canadianCitizen;
bool firstTimeBuyer;
}
struct Taxes {
uint256 provinceTaxes;
uint256 cityTaxes;
uint256 mortgageInsurance;
}
modifier onlyPropertyOwner {
require(msg.sender == propertyOwner);
_;
}
modifier onlyPropertyBuyer {
require(msg.sender == prospectiveSale.buyer);
_;
}
event CalculateTaxes( address indexed _seller, address indexed _buyer,
string _registrationNumber, string _province, string _city,
uint256 _salePrice, uint256 _downpayment, bool _optForInsurance,
uint256 _buyerAge, bool _buyerCanadianCitizen, bool _buyerFirstTime );
State public state;
address public propertyOwner;
address public cityWallet;
address public provinceWallet;
address public insurerWallet;
PropertyAddress public propertyAddress;
ProspectiveSale public prospectiveSale;
ProspectiveBuyer public prospectiveBuyer;
Taxes public taxes;
function PropertyRegistry( address _propertyOwner, address _cityWallet, address _provinceWallet,
address _insurerWallet,
string _registrationNumber, string _streetAddress, string _city,
string _province ) public {
state = State.OWNED;
propertyOwner = _propertyOwner;
cityWallet = _cityWallet;
provinceWallet = _provinceWallet;
insurerWallet = _insurerWallet;
propertyAddress = PropertyAddress( _registrationNumber, _streetAddress, _city, _province );
}
function cancelSale() public onlyPropertyOwner {
state = State.OWNED;
}
function initiateSale( address _buyer, uint256 _salePrice, uint256 _exchangeRate ) public onlyPropertyOwner returns (bool success) {
// initiate the sale process
if( state != State.OWNED ) return false;
prospectiveSale = ProspectiveSale( _buyer, _salePrice, _exchangeRate );
state = State.SALE_INITIATED;
return true;
}
function submitBuyerInformation( string _name, uint _age, bool _canadianCitizen, bool _firstTimeBuyer,
uint256 _downpayment, bool _optForInsurance ) public onlyPropertyBuyer returns (bool success) {
// submits the buyer information for calculation of taxes
if( state != State.SALE_INITIATED ) return false;
prospectiveBuyer = ProspectiveBuyer( _name, _age, _canadianCitizen, _firstTimeBuyer );
CalculateTaxes( propertyOwner, prospectiveSale.buyer,
propertyAddress.registrationNumber, propertyAddress.province, propertyAddress.city,
prospectiveSale.salePrice, _downpayment, _optForInsurance,
_age, _canadianCitizen, _firstTimeBuyer );
state = State.CALCULATING_TAXES;
return true;
}
function setTaxAmount( uint256 _provinceTaxes, uint256 _cityTaxes, uint256 _mortgageInsurance ) public returns (bool success) {
// sets the values of taxes for the sale
if( state != State.CALCULATING_TAXES ) return false;
taxes = Taxes( _provinceTaxes, _cityTaxes, _mortgageInsurance );
state = State.WAITING_FINALIZATION;
return true;
}
function finalizeSale( ) public payable onlyPropertyBuyer returns (bool success) {
// finalizes the payment and transfer of property
if( state != State.WAITING_FINALIZATION ) revert();
uint256 salePriceWei = convertToWei( prospectiveSale.salePrice, prospectiveSale.exchangeRate );
uint256 provinceWei = convertToWei( taxes.provinceTaxes, prospectiveSale.exchangeRate );
uint256 cityWei = convertToWei( taxes.cityTaxes, prospectiveSale.exchangeRate );
uint256 insuranceWei = convertToWei( taxes.mortgageInsurance, prospectiveSale.exchangeRate );
uint256 totalWei = salePriceWei + provinceWei + cityWei + insuranceWei;
if( msg.value < totalWei ) revert();
if( provinceWei > 0 && ! provinceWallet.send( provinceWei ) ) revert();
if( cityWei > 0 && ! cityWallet.send( cityWei ) ) revert();
if( insuranceWei > 0 && ! insurerWallet.send( insuranceWei ) ) revert();
if( salePriceWei > 0 && ! propertyOwner.send( salePriceWei ) ) revert();
propertyOwner = prospectiveSale.buyer;
state = State.OWNED;
return true;
}
function convertToWei(uint256 dollarAmount, uint256 conversionRate) public pure returns (uint convertedAmount) {
return dollarAmount * 1e18 / conversionRate ;
}
function totalAmountWei() public view returns (uint totalWei) {
if( state != State.WAITING_FINALIZATION ) return 0;
uint256 salePriceWei = convertToWei( prospectiveSale.salePrice, prospectiveSale.exchangeRate );
uint256 provinceWei = convertToWei( taxes.provinceTaxes, prospectiveSale.exchangeRate );
uint256 cityWei = convertToWei( taxes.provinceTaxes, prospectiveSale.exchangeRate );
uint256 insuranceWei = convertToWei( taxes.provinceTaxes, prospectiveSale.exchangeRate );
uint256 total = salePriceWei + provinceWei + cityWei + insuranceWei;
return total;
}
}
| submits the buyer information for calculation of taxes | function submitBuyerInformation( string _name, uint _age, bool _canadianCitizen, bool _firstTimeBuyer,
uint256 _downpayment, bool _optForInsurance ) public onlyPropertyBuyer returns (bool success) {
if( state != State.SALE_INITIATED ) return false;
prospectiveBuyer = ProspectiveBuyer( _name, _age, _canadianCitizen, _firstTimeBuyer );
CalculateTaxes( propertyOwner, prospectiveSale.buyer,
propertyAddress.registrationNumber, propertyAddress.province, propertyAddress.city,
prospectiveSale.salePrice, _downpayment, _optForInsurance,
_age, _canadianCitizen, _firstTimeBuyer );
state = State.CALCULATING_TAXES;
return true;
}
| 7,302,470 | [
1,
1717,
22679,
326,
27037,
1779,
364,
11096,
434,
5320,
281,
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,
4879,
38,
16213,
5369,
12,
533,
389,
529,
16,
2254,
389,
410,
16,
1426,
389,
4169,
361,
2779,
39,
305,
452,
275,
16,
1426,
389,
3645,
950,
38,
16213,
16,
203,
19694,
2254,
5034,
389,
2378,
9261,
16,
1426,
389,
3838,
1290,
5048,
295,
1359,
262,
1071,
1338,
1396,
38,
16213,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
309,
12,
919,
480,
3287,
18,
5233,
900,
67,
12919,
45,
6344,
262,
327,
629,
31,
203,
3639,
450,
13234,
688,
38,
16213,
273,
1186,
13234,
688,
38,
16213,
12,
389,
529,
16,
389,
410,
16,
389,
4169,
361,
2779,
39,
305,
452,
275,
16,
389,
3645,
950,
38,
16213,
11272,
203,
203,
3639,
9029,
7731,
281,
12,
1272,
5541,
16,
450,
13234,
688,
30746,
18,
70,
16213,
16,
203,
13491,
1272,
1887,
18,
14170,
1854,
16,
1272,
1887,
18,
25529,
2410,
16,
1272,
1887,
18,
14240,
16,
203,
13491,
450,
13234,
688,
30746,
18,
87,
5349,
5147,
16,
389,
2378,
9261,
16,
389,
3838,
1290,
5048,
295,
1359,
16,
203,
13491,
389,
410,
16,
389,
4169,
361,
2779,
39,
305,
452,
275,
16,
389,
3645,
950,
38,
16213,
11272,
203,
3639,
919,
273,
3287,
18,
7913,
39,
1506,
28054,
67,
56,
2501,
3991,
31,
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
] |
./full_match/5/0xc2166567dbCC8Bc35ce79Ed429D75451AfC14985/sources/localhost/contracts/GatebridgeV2LPToken.sol | update reserves and, on the first call per block, price accumulators uint32 timeElapsed = blockTimestamp - blockTimestampLast; overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve1 = uint112(balance1); | function _updateAdd(uint amount) private {
require(amount <= uint112(-1), 'GatebridgeV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
reserve = reserve + uint112(amount);
blockTimestampLast = blockTimestamp;
emit Sync(reserve);
}
| 1,852,282 | [
1,
2725,
400,
264,
3324,
471,
16,
603,
326,
1122,
745,
1534,
1203,
16,
6205,
8822,
3062,
3639,
2254,
1578,
813,
28827,
273,
1203,
4921,
300,
1203,
4921,
3024,
31,
225,
9391,
353,
6049,
3639,
309,
261,
957,
28827,
405,
374,
597,
389,
455,
6527,
20,
480,
374,
597,
389,
455,
6527,
21,
480,
374,
13,
288,
2868,
5903,
9391,
87,
16,
471,
397,
9391,
353,
6049,
5411,
6205,
20,
39,
11276,
3024,
1011,
2254,
12,
57,
53,
17666,
92,
17666,
18,
3015,
24899,
455,
6527,
21,
2934,
89,
85,
2892,
24899,
455,
6527,
20,
3719,
225,
813,
28827,
31,
5411,
6205,
21,
39,
11276,
3024,
1011,
2254,
12,
57,
53,
17666,
92,
17666,
18,
3015,
24899,
455,
6527,
20,
2934,
89,
85,
2892,
24899,
455,
6527,
21,
3719,
225,
813,
28827,
31,
3639,
289,
3639,
20501,
21,
273,
2254,
17666,
12,
12296,
21,
1769,
2,
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,
1,
1,
1,
1,
1,
0,
0,
0,
0
] | [
1,
565,
445,
389,
2725,
986,
12,
11890,
3844,
13,
3238,
288,
203,
3639,
2583,
12,
8949,
1648,
2254,
17666,
19236,
21,
3631,
296,
13215,
18337,
58,
22,
30,
22577,
17430,
8284,
203,
3639,
2254,
1578,
1203,
4921,
273,
2254,
1578,
12,
2629,
18,
5508,
738,
576,
636,
1578,
1769,
203,
3639,
20501,
273,
20501,
397,
2254,
17666,
12,
8949,
1769,
203,
3639,
1203,
4921,
3024,
273,
1203,
4921,
31,
203,
3639,
3626,
9721,
12,
455,
6527,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@boringcrypto/boring-solidity-e06e943/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity-e06e943/contracts/BoringBatchable.sol";
import "@boringcrypto/boring-solidity-e06e943/contracts/BoringOwnable.sol";
import "../libraries/SignedSafeMath.sol";
import "../interfaces/IRewarder.sol";
import "../interfaces/IMasterChef.sol";
/// @notice The (older) MasterChef contract gives out a constant number of JIO tokens per block.
/// It is the only address with minting rights for JIO.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives.
contract MiniChefV2 is BoringOwnable, BoringBatchable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of JIO entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of JIO to distribute per block.
struct PoolInfo {
uint128 accJioPerShare;
uint64 lastRewardTime;
uint64 allocPoint;
}
/// @notice Address of JIO contract.
IERC20 public immutable JIO;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public jioPerSecond;
uint256 private constant ACC_JIO_PRECISION = 1e12;
event Deposit(
address indexed user,
uint256 indexed pid,
uint256 amount,
address indexed to
);
event Withdraw(
address indexed user,
uint256 indexed pid,
uint256 amount,
address indexed to
);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount,
address indexed to
);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(
uint256 indexed pid,
uint256 allocPoint,
IERC20 indexed lpToken,
IRewarder indexed rewarder
);
event LogSetPool(
uint256 indexed pid,
uint256 allocPoint,
IRewarder indexed rewarder,
bool overwrite
);
event LogUpdatePool(
uint256 indexed pid,
uint64 lastRewardTime,
uint256 lpSupply,
uint256 accJioPerShare
);
event LogJioPerSecond(uint256 jioPerSecond);
/// @param _jio The JIO token contract address.
constructor(IERC20 _jio) public {
JIO = _jio;
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({
allocPoint: allocPoint.to64(),
lastRewardTime: block.timestamp.to64(),
accJioPerShare: 0
})
);
emit LogPoolAddition(
lpToken.length.sub(1),
allocPoint,
_lpToken,
_rewarder
);
}
/// @notice Update the given pool's JIO allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(
_pid,
_allocPoint,
overwrite ? _rewarder : rewarder[_pid],
overwrite
);
}
/// @notice Sets the jio per second to be distributed. Can only be called by the owner.
/// @param _jioPerSecond The amount of Jio to be distributed per second.
function setJioPerSecond(uint256 _jioPerSecond) public onlyOwner {
jioPerSecond = _jioPerSecond;
emit LogJioPerSecond(_jioPerSecond);
}
/// @notice View function to see pending JIO on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending JIO reward for a given user.
function pendingJio(uint256 _pid, address _user)
external
view
returns (uint256 pending)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accJioPerShare = pool.accJioPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
uint256 time = block.timestamp.sub(pool.lastRewardTime);
uint256 jioReward = time.mul(jioPerSecond).mul(
pool.allocPoint
) / totalAllocPoint;
accJioPerShare = accJioPerShare.add(
jioReward.mul(ACC_JIO_PRECISION) / lpSupply
);
}
pending = int256(
user.amount.mul(accJioPerShare) / ACC_JIO_PRECISION
).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.timestamp > pool.lastRewardTime) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 time = block.timestamp.sub(pool.lastRewardTime);
uint256 jioReward = time.mul(jioPerSecond).mul(
pool.allocPoint
) / totalAllocPoint;
pool.accJioPerShare = pool.accJioPerShare.add(
(jioReward.mul(ACC_JIO_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardTime = block.timestamp.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(
pid,
pool.lastRewardTime,
lpSupply,
pool.accJioPerShare
);
}
}
/// @notice Deposit LP tokens to MCV2 for JIO allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(
int256(amount.mul(pool.accJioPerShare) / ACC_JIO_PRECISION)
);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onJioReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(
int256(amount.mul(pool.accJioPerShare) / ACC_JIO_PRECISION)
);
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onJioReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of JIO rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedJio = int256(
user.amount.mul(pool.accJioPerShare) / ACC_JIO_PRECISION
);
uint256 _pendingJio = accumulatedJio
.sub(user.rewardDebt)
.toUInt256();
// Effects
user.rewardDebt = accumulatedJio;
// Interactions
if (_pendingJio != 0) {
JIO.safeTransfer(to, _pendingJio);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onJioReward(
pid,
msg.sender,
to,
_pendingJio,
user.amount
);
}
emit Harvest(msg.sender, pid, _pendingJio);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and JIO rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedJio = int256(
user.amount.mul(pool.accJioPerShare) / ACC_JIO_PRECISION
);
uint256 _pendingJio = accumulatedJio
.sub(user.rewardDebt)
.toUInt256();
// Effects
user.rewardDebt = accumulatedJio.sub(
int256(amount.mul(pool.accJioPerShare) / ACC_JIO_PRECISION)
);
user.amount = user.amount.sub(amount);
// Interactions
JIO.safeTransfer(to, _pendingJio);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onJioReward(
pid,
msg.sender,
to,
_pendingJio,
user.amount
);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingJio);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onJioReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
}
| @notice Add a new LP to the pool. Can only be called by the owner. DO NOT add the same LP token more than once. Rewards will be messed up if you do. @param allocPoint AP of the new pool. @param _lpToken Address of the LP ERC-20 token. @param _rewarder Address of the rewarder delegate. | function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({
allocPoint: allocPoint.to64(),
lastRewardTime: block.timestamp.to64(),
accJioPerShare: 0
})
);
emit LogPoolAddition(
lpToken.length.sub(1),
allocPoint,
_lpToken,
_rewarder
);
}
| 12,724,889 | [
1,
986,
279,
394,
511,
52,
358,
326,
2845,
18,
4480,
1338,
506,
2566,
635,
326,
3410,
18,
5467,
4269,
527,
326,
1967,
511,
52,
1147,
1898,
2353,
3647,
18,
534,
359,
14727,
903,
506,
15216,
730,
731,
309,
1846,
741,
18,
225,
4767,
2148,
14410,
434,
326,
394,
2845,
18,
225,
389,
9953,
1345,
5267,
434,
326,
511,
52,
4232,
39,
17,
3462,
1147,
18,
225,
389,
266,
20099,
5267,
434,
326,
283,
20099,
7152,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
527,
12,
203,
3639,
2254,
5034,
4767,
2148,
16,
203,
3639,
467,
654,
39,
3462,
389,
9953,
1345,
16,
203,
3639,
15908,
359,
297,
765,
389,
266,
20099,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
2078,
8763,
2148,
273,
2078,
8763,
2148,
18,
1289,
12,
9853,
2148,
1769,
203,
3639,
12423,
1345,
18,
6206,
24899,
9953,
1345,
1769,
203,
3639,
283,
20099,
18,
6206,
24899,
266,
20099,
1769,
203,
203,
3639,
2845,
966,
18,
6206,
12,
203,
5411,
8828,
966,
12590,
203,
7734,
4767,
2148,
30,
4767,
2148,
18,
869,
1105,
9334,
203,
7734,
1142,
17631,
1060,
950,
30,
1203,
18,
5508,
18,
869,
1105,
9334,
203,
7734,
4078,
46,
1594,
2173,
9535,
30,
374,
203,
5411,
289,
13,
203,
3639,
11272,
203,
3639,
3626,
1827,
2864,
30296,
12,
203,
5411,
12423,
1345,
18,
2469,
18,
1717,
12,
21,
3631,
203,
5411,
4767,
2148,
16,
203,
5411,
389,
9953,
1345,
16,
203,
5411,
389,
266,
20099,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 LinkedListLib
* @author Darryl Morris (o0ragman0o) and Modular.network
*
* This utility library was forked from https://github.com/o0ragman0o/LibCLL
* into the Modular-Network ethereum-libraries repo at https://github.com/Modular-Network/ethereum-libraries
* It has been updated to add additional functionality and be more compatible with solidity 0.4.18
* coding patterns.
*
* version 1.0.0
* Copyright (c) 2017 Modular Inc.
* The MIT License (MIT)
* https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE
*
* The LinkedListLib provides functionality for implementing data indexing using
* a circlular linked list
*
* Modular provides smart contract services and security reviews for contract
* deployments in addition to working on open source projects in the Ethereum
* community. Our purpose is to test, document, and deploy reusable code onto the
* blockchain and improve both security and usability. We also educate non-profits,
* schools, and other community members about the application of blockchain
* technology. For further information: modular.network
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
library LinkedListLib {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct LinkedList{
mapping (uint256 => mapping (bool => uint256)) list;
}
/// @dev returns true if the list exists
/// @param self stored linked list from contract
function listExists(LinkedList storage self)
internal
view returns (bool)
{
// if the head nodes previous or next pointers both point to itself, then there are no items in the list
if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) {
return true;
} else {
return false;
}
}
/// @dev returns true if the node exists
/// @param self stored linked list from contract
/// @param _node a node to search for
function nodeExists(LinkedList storage self, uint256 _node)
internal
view returns (bool)
{
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
/// @dev Returns the number of elements in the list
/// @param self stored linked list from contract
function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) {
bool exists;
uint256 i;
(exists,i) = getAdjacent(self, HEAD, NEXT);
while (i != HEAD) {
(exists,i) = getAdjacent(self, i, NEXT);
numElements++;
}
return;
}
/// @dev Returns the links of a node as a tuple
/// @param self stored linked list from contract
/// @param _node id of the node to get
function getNode(LinkedList storage self, uint256 _node)
internal view returns (bool,uint256,uint256)
{
if (!nodeExists(self,_node)) {
return (false,0,0);
} else {
return (true,self.list[_node][PREV], self.list[_node][NEXT]);
}
}
/// @dev Returns the link of a node `_node` in direction `_direction`.
/// @param self stored linked list from contract
/// @param _node id of the node to step from
/// @param _direction direction to step in
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
internal view returns (bool,uint256)
{
if (!nodeExists(self,_node)) {
return (false,0);
} else {
return (true,self.list[_node][_direction]);
}
}
/// @dev Can be used before `insert` to build an ordered list
/// @param self stored linked list from contract
/// @param _node an existing node to search from, e.g. HEAD.
/// @param _value value to seek
/// @param _direction direction to seek in
// @return next first node beyond '_node' in direction `_direction`
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
internal view returns (uint256)
{
if (sizeOf(self) == 0) { return 0; }
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];
return next;
}
/// @dev Can be used before `insert` to build an ordered list
/// @param self stored linked list from contract
/// @param _node an existing node to search from, e.g. HEAD.
/// @param _value value to seek
/// @param _direction direction to seek in
// @return next first node beyond '_node' in direction `_direction`
function getSortedSpotByFunction(LinkedList storage self, uint256 _node, uint256 _value, bool _direction, function (uint, uint) view returns (bool) smallerComparator, int256 searchLimit)
internal view returns (uint256 nextNodeIndex, bool found, uint256 sizeEnd)
{
if ((sizeEnd=sizeOf(self)) == 0) { return (0, true, sizeEnd); }
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((--searchLimit >= 0) && (next != 0) && (_value != next) && (smallerComparator(_value, next) != _direction)) next = self.list[next][_direction];
if(searchLimit >= 0)
return (next, true, sizeEnd + 1);
else return (0, false, sizeEnd); //We exhausted the search limit without finding a position!
}
/// @dev Creates a bidirectional link between two nodes on direction `_direction`
/// @param self stored linked list from contract
/// @param _node first node for linking
/// @param _link node to link to in the _direction
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) internal {
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
/// @dev Insert node `_new` beside existing node `_node` in direction `_direction`.
/// @param self stored linked list from contract
/// @param _node existing node
/// @param _new new node to insert
/// @param _direction direction to insert node in
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) {
if(!nodeExists(self,_new) && nodeExists(self,_node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
return true;
} else {
return false;
}
}
/// @dev removes an entry from the linked list
/// @param self stored linked list from contract
/// @param _node node to remove from the list
function remove(LinkedList storage self, uint256 _node) internal returns (uint256) {
if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; }
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
return _node;
}
/// @dev pushes an enrty to the head of the linked list
/// @param self stored linked list from contract
/// @param _node new entry to push to the head
/// @param _direction push to the head (NEXT) or tail (PREV)
function push(LinkedList storage self, uint256 _node, bool _direction) internal {
insert(self, HEAD, _node, _direction);
}
/// @dev pops the first entry from the linked list
/// @param self stored linked list from contract
/// @param _direction pop from the head (NEXT) or the tail (PREV)
function pop(LinkedList storage self, bool _direction) internal returns (uint256) {
bool exists;
uint256 adj;
(exists,adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
// ----------------------------------------------------------------------------
// 'Coke' token contract
//
// Deployed to : 0xb9907e0151e8c5937f17d0721953cf1ea114528e
// Symbol : COKE
// Name : Coke Token
// Total supply: 875 000 000 000 000 micrograms (875 tons)
// Decimals : 6 (micrograms)
//
// @2018 FC
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a && c >= b);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
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;
}
}
contract Mutex {
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
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 function to receive approval and execute function in one call
//
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// Contract "Recoverable", to allow a failsafe in case of user error, so users can recover their mistakenly sent Tokens or Eth
// https://github.com/ethereum/dapp-bin/blob/master/library/recoverable.sol
// ----------------------------------------------------------------------------
contract Recoverable is Owned {
// ------------------------------------------------------------------------
// 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);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ETH
// ------------------------------------------------------------------------
function recoverLostEth(address toAddress, uint value) public onlyOwner returns (bool success) {
toAddress.transfer(value);
return true;
}
}
/**
* @title EmergencyProtectedMode
* @dev Base contract which allows children to implement an emergency stop mechanism different than pausable. Useful for when we want to
* stop the normal business of the contract (using the Pausable contract), but still allow some operations like withdrawls for users.
*/
contract EmergencyProtectedMode is Owned {
event EmergencyProtectedModeActivated();
event EmergencyProtectedModeDeactivated();
bool public emergencyProtectedMode = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotInEmergencyProtectedMode() {
require(!emergencyProtectedMode);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenInEmergencyProtectedMode() {
require(emergencyProtectedMode);
_;
}
/**
* @dev called by the owner to activate emergency protected mode, triggers stopped state, to use in case of last resort, and stop even last case operations (in case of a security compromise)
*/
function activateEmergencyProtectedMode() onlyOwner whenNotInEmergencyProtectedMode public {
emergencyProtectedMode = true;
emit EmergencyProtectedModeActivated();
}
/**
* @dev called by the owner to deactivate emergency protected mode, returns to normal state
*/
function deactivateEmergencyProtectedMode() onlyOwner whenInEmergencyProtectedMode public {
emergencyProtectedMode = false;
emit EmergencyProtectedModeDeactivated();
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Owned {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Migratable
* @dev Base contract which allows children to be migratable, that is it allows contracts to migrate to another contract (sucessor) that
* is a more advanced version of the previous contract (more functionality, improved security, etc.).
*/
contract Migratable is Owned {
address public sucessor; //By default, sucessor will be address 0, meaning the current contract is still active and has no sucessor yet!
function setSucessor(address _sucessor) onlyOwner public {
sucessor=_sucessor;
}
}
// ---------------------------------------------------------------------------------------------
// Directly Exchangeable token
// This will allow users to directly exchange between themselves tokens for Eth and vice versa,
// while having the assurance the other party will be kept to their part of the agreement.
// ---------------------------------------------------------------------------------------------
contract DirectlyExchangeable {
bool public isRatio; //Should be true if the prices used will be a Ratio, and not just a simple price, otherwise false.
function sellToConsumer(address consumer, uint quantity, uint price) public returns (bool success);
function buyFromTrusterDealer(address dealer, uint quantity, uint price) public payable returns (bool success);
function cancelSellToConsumer(address consumer) public returns (bool success);
function checkMySellerOffer(address consumer) public view returns (uint quantity, uint price, uint totalWeiCost);
function checkSellerOffer(address seller) public view returns (uint quantity, uint price, uint totalWeiCost);
//Events:
event DirectOfferAvailable(address indexed seller, address indexed buyer, uint quantity, uint price);
event DirectOfferCancelled(address indexed seller, address indexed consumer, uint quantity, uint price);
event OrderQuantityMismatch(address indexed addr, uint expectedInRegistry, uint buyerValue);
event OrderPriceMismatch(address indexed addr, uint expectedInRegistry, uint buyerValue);
}
// ---------------------------------------------------------------------------------------------
// Black Market Sellable token
// This will allow users to sell and buy from a black market, without knowing one another,
// while having the assurance the other party will keep their part of the agreement.
// ---------------------------------------------------------------------------------------------
contract BlackMarketSellable {
bool public isRatio; //Should be true if the prices used will be a Ratio, and not just a simple price, otherwise false.
function sellToBlackMarket(uint quantity, uint price) public returns (bool success, uint numOrderCreated);
function cancelSellToBlackMarket(uint quantity, uint price, bool continueAfterFirstMatch) public returns (bool success, uint numOrdersCanceled);
function buyFromBlackMarket(uint quantity, uint priceLimit) public payable returns (bool success, bool partial, uint numOrdersCleared);
function getSellOrdersBlackMarket() public view returns (uint[] memory r);
function getSellOrdersBlackMarketComplete() public view returns (uint[] memory quantities, uint[] memory prices);
function getMySellOrdersBlackMarketComplete() public view returns (uint[] memory quantities, uint[] memory prices);
//Events:
event BlackMarketOfferAvailable(uint quantity, uint price);
event BlackMarketOfferBought(uint quantity, uint price, uint leftOver);
event BlackMarketNoOfferForPrice(uint price);
event BlackMarketOfferCancelled(uint quantity, uint price);
event OrderInsufficientPayment(address indexed addr, uint expectedValue, uint valueReceived);
event OrderInsufficientBalance(address indexed addr, uint expectedBalance, uint actualBalance);
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract Coke is ERC20Interface, Owned, Pausable, EmergencyProtectedMode, Recoverable, Mutex, Migratable, DirectlyExchangeable, BlackMarketSellable, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
//Needed setup for LinkedList needed for the market:
using LinkedListLib for LinkedListLib.LinkedList;
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
//Token specific properties:
uint16 public constant yearOfProduction = 1997;
string public constant protectedDenominationOfOrigin = "Colombia";
string public constant targetDemographics = "The jet set / Top of the tops";
string public constant securityAudit = "ExtremeAssets Team Ref: XN872 Approved";
uint buyRatio; //Ratio to buy from the contract directly
uint sellRatio; //Ratio to sell from the contract directly
uint private _factorDecimalsEthToToken;
uint constant undergroundBunkerReserves = 2500000000000;
mapping(address => uint) changeToReturn; //The change to return to senders (in ETH value (Wei))
mapping(address => uint) gainsToReceive; //The gains to receive (for sellers) (in ETH value (Wei))
mapping(address => uint) tastersReceived; //Number of tokens received as a taster for each address
mapping(address => uint) toFlush; //Keeps address to be flushed (the value stored is the number of the block of when coke can be really flushed from the system)
event Flushed(address indexed addr);
event ChangeToReceiveGotten(address indexed addr, uint weiToReceive, uint totalWeiToReceive);
event GainsGotten(address indexed addr, uint weiToReceive, uint totalWeiToReceive);
struct SellOffer {
uint price;
uint quantity;
}
struct SellOfferComplete {
uint price;
uint quantity;
address seller;
}
mapping(address => mapping(address => SellOffer)) directOffers; //Direct offers
LinkedListLib.LinkedList blackMarketOffersSorted;
mapping(uint => SellOfferComplete) public blackMarketOffersMap;
uint marketOfferCounter = 0; //Counter that will increment for each offer
uint directOffersComissionRatio = 100; //Ratio of the comission to buy from the contract directly (1%)
uint marketComissionRatio = 50; //Ratio of the comission to buy from the market (2%)
int32 maxMarketOffers = 100; //Maximum of market offers at the same time (will only keep the N less costly offers)
//Message board variables:
struct Message {
uint valuePayed;
string msg;
address from;
}
LinkedListLib.LinkedList topMessagesSorted;
mapping(uint => Message) public topMessagesMap;
uint topMessagesCounter = 0; //Counter that will increment for each message
int32 maxMessagesTop = 20; //Maximum of top messages at the same time (will keep the N most payed messages)
Message[] messages;
int32 maxMessagesGlobal = 100; //Maximum number of messages at the same time (will keep the N most recently received messages)
int32 firstMsgGlobal = 0; //Indexes that will mark the first and the last message received in the array of global messages (revolving array)
int32 lastMsgGlobal = -1;
uint maxCharactersMessage = 750; //The maximum of characters a message can have
event NewMessageAvailable(address indexed from, string message);
event ExceededMaximumMessageSize(uint messageSize, uint maximumMessageSize); //Message is bigger than maximum allowed characters for each message
//Addresses to be used for random letItRain!
address[] lastAddresses;
int32 maxAddresses = 100; //Maximum number of addresses at the same time (will keep the N most recently mentioned addresses)
int32 firstAddress = 0; //Indexes that will mark the first and the last address received in the array of last addresses (revolving array)
int32 lastAddress = -1;
event NoAddressesAvailable();
// ------------------------------------------------------------------------
// Confirms the user is not in the middle of a flushing process
// ------------------------------------------------------------------------
modifier whenNotFlushing() {
require(toFlush[msg.sender] == 0);
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Coke() public {
symbol = "Coke";
name = "100 % Pure Cocaine";
decimals = 6; //Micrograms
_totalSupply = 875000000 * (uint(10)**decimals);
_factorDecimalsEthToToken = uint(10)**(18);
buyRatio = 10 * (uint(10)**decimals); //10g <- 1 ETH
sellRatio = 20 * (uint(10)**decimals); //20g -> 1 ETH
isRatio = true; //Buy and sell prices are ratios (and not simple prices) of how many tokens per 1 ETH
balances[0] = _totalSupply - undergroundBunkerReserves;
balances[msg.sender] = undergroundBunkerReserves;
//blackMarketOffers.length = maxMarketOffers;
//Do a reservation for msg.sender! Allow rest to be sold by contract!
emit Transfer(address(0), msg.sender, undergroundBunkerReserves);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply /* - balances[address(0)] */;
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transferInt(address from, address to, uint tokens, bool updateTasters) internal returns (bool success) {
if(updateTasters) {
//Check if sender has received tasters:
if(tastersReceived[from] > 0) {
uint tasterTokens = min(tokens, tastersReceived[from]);
tastersReceived[from] = safeSub(tastersReceived[from], tasterTokens);
if(to != address(0)) {
tastersReceived[to] = safeAdd(tastersReceived[to], tasterTokens);
}
}
}
balances[from] = safeSub(balances[from], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public whenNotPaused returns (bool success) {
return transferInt(msg.sender, to, tokens, true);
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public whenNotPaused returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool success) {
//Update the allowance, the rest it business as usual for the transferInt method:
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
return transferInt(from, to, tokens, true);
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant whenNotPaused returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public whenNotPaused returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Calculates the number of tokens (in unsigned integer form [decimals included]) corresponding to the weiValue passed, using the ratio specified
// ------------------------------------------------------------------------
function calculateTokensFromWei(uint weiValue, uint ratio) public view returns (uint numTokens) {
uint calc1 = safeMul(weiValue, ratio);
uint ethValue = calc1 / _factorDecimalsEthToToken;
return ethValue;
}
// ------------------------------------------------------------------------
// Calculates the Eth value (in wei) corresponding to the number of tokens passed (in unsigned integer form [decimals included]), using the ratio specified
// ------------------------------------------------------------------------
function calculateEthValueFromTokens(uint numTokens, uint ratio) public view returns (uint weiValue) {
uint calc1 = safeMul(numTokens, _factorDecimalsEthToToken);
uint retValue = calc1 / ratio;
return retValue;
}
// ------------------------------------------------------------------------
// Will buy tokens corresponding to the Ether sent (Own Token Specific Method)
// - Contract supply of tokens must have enough balance
// ------------------------------------------------------------------------
function buyCoke() public payable returns (bool success) {
//Calculate tokens corresponding to the Ether sent:
uint numTokensToBuy = calculateTokensFromWei(msg.value, buyRatio);
uint finalNumTokensToBuy = numTokensToBuy;
if(numTokensToBuy > balances[0]) {
//Adjust number of tokens to buy, to those available in stock:
finalNumTokensToBuy = balances[0];
//Update change to return for this sender (in Wei):
//SAFETY CHECK: No need to use safeSub for (numTokensToBuy - finalNumTokensToBuy), as we already know that numTokensToBuy > finalNumTokensToBuy!
uint ethValueFromTokens = calculateEthValueFromTokens(numTokensToBuy - finalNumTokensToBuy, buyRatio); //In Wei
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], ethValueFromTokens );
emit ChangeToReceiveGotten(msg.sender, ethValueFromTokens, changeToReturn[msg.sender]);
}
if(finalNumTokensToBuy <= balances[0]) {
/*
balances[0] = safeSub(balances[0], finalNumTokensToBuy);
balances[msg.sender] = safeAdd(balances[msg.sender], finalNumTokensToBuy);
Transfer(address(0), msg.sender, finalNumTokensToBuy);
*/
transferInt(address(0), msg.sender, finalNumTokensToBuy, false);
return true;
}
else return false;
}
// ------------------------------------------------------------------------
// Will show to the user that is asking the change he has to receive
// ------------------------------------------------------------------------
function checkChangeToReceive() public view returns (uint changeInWei) {
return changeToReturn[msg.sender];
}
// ------------------------------------------------------------------------
// Will show to the user that is asking the gains he has to receive
// ------------------------------------------------------------------------
function checkGainsToReceive() public view returns (uint gainsInWei) {
return gainsToReceive[msg.sender];
}
// ------------------------------------------------------------------------
// Will get change in ETH from the tokens that were not possible to buy in a previous order
// - Contract supply of ETH must have enough balance (which should be in every case)
// ------------------------------------------------------------------------
function retrieveChange() public noReentrancy whenNotInEmergencyProtectedMode returns (bool success) {
uint change = changeToReturn[msg.sender];
if(change > 0) {
//Set correct value of change before calling transfer method to avoid reentrance after sending to another contracts:
changeToReturn[msg.sender] = 0;
//Send corresponding ETH to sender:
msg.sender.transfer(change);
return true;
}
else return false;
}
// ------------------------------------------------------------------------
// Will get gains in ETH from the tokens that the seller has previously sold
// - Contract supply of ETH must have enough balance (which should be in every case)
// ------------------------------------------------------------------------
function retrieveGains() public noReentrancy whenNotInEmergencyProtectedMode returns (bool success) {
uint gains = gainsToReceive[msg.sender];
if(gains > 0) {
//Set correct value of "gains to receive" before calling transfer method to avoid reentrance attack after possibly sending to another contract:
gainsToReceive[msg.sender] = 0;
//Send corresponding ETH to sender:
msg.sender.transfer(gains);
return true;
}
else return false;
}
// ------------------------------------------------------------------------
// Will return N bought tokens to the contract
// - User supply of tokens must have enough balance
// ------------------------------------------------------------------------
function returnCoke(uint ugToReturn) public noReentrancy whenNotPaused whenNotFlushing returns (bool success) {
//require(ugToReturn <= balances[msg.sender]); //Check balance of user
//Following require not needed anymore, will just pay the difference!
//require(ugToReturn > tastersReceived[msg.sender]); //Check if the mg to return are greater than the ones received as a taster
//Maximum possible number of mg to return, have to be lower than the balance of the user minus the tasters received:
uint finalUgToReturnForEth = min(ugToReturn, safeSub(balances[msg.sender], tastersReceived[msg.sender])); //Subtract tasters received from the total amount to return
//require(finalUgToReturnForEth <= balances[msg.sender]); //Check balance of user (No need for this extra check, as the minimum garantees at most the value of the balance[] to be returned)
//Calculate tokens corresponding to the Ether sent:
uint ethToReturn = calculateEthValueFromTokens(finalUgToReturnForEth, sellRatio); //Ethereum to return (in Wei)
if(ethToReturn > 0) {
//Will return eth in exchange for the coke!
//Receive the coke:
transfer(address(0), finalUgToReturnForEth);
/*
balances[0] = safeAdd(balances[0], finalUgToReturnForEth);
balances[msg.sender] = safeSub(balances[msg.sender], finalUgToReturnForEth);
Transfer(msg.sender, address(0), finalUgToReturnForEth);
*/
//Return the Eth:
msg.sender.transfer(ethToReturn);
return true;
}
else return false;
}
// ------------------------------------------------------------------------
// Will return all bought tokens to the contract
// ------------------------------------------------------------------------
function returnAllCoke() public returns (bool success) {
return returnCoke(safeSub(balances[msg.sender], tastersReceived[msg.sender]));
}
// ------------------------------------------------------------------------
// Sends a special taster package to recipient
// - Contract supply of tokens must have enough balance
// ------------------------------------------------------------------------
function sendSpecialTasterPackage(address addr, uint ugToTaste) public whenNotPaused onlyOwner returns (bool success) {
tastersReceived[addr] = safeAdd(tastersReceived[addr], ugToTaste);
transfer(addr, ugToTaste);
return true;
}
// ------------------------------------------------------------------------
// Will transfer to selected address a load of tokens
// - User supply of tokens must have enough balance
// ------------------------------------------------------------------------
function sendShipmentTo(address to, uint tokens) public returns (bool success) {
return transfer(to, tokens);
}
// ------------------------------------------------------------------------
// Will transfer a small sample to selected address
// - User supply of tokens must have enough balance
// ------------------------------------------------------------------------
function sendTaster(address to) public returns (bool success) {
//Sending in 0.000002 g (that is 2 micrograms):
return transfer(to, 2);
}
function lengthAddresses() internal view returns (uint) {
return (firstAddress > 0) ? lastAddresses.length : uint(lastAddress + 1);
}
// ------------------------------------------------------------------------
// Will make it rain! Will throw some tokens from the user to some random addresses, spreading the happiness everywhere!
// The greater the range, it will supply to addresses further away.
// - User supply of tokens must have enough balance
// ------------------------------------------------------------------------
function letItRain(uint8 range, uint quantity) public returns (bool success) {
require(quantity <= balances[msg.sender]);
if(lengthAddresses() == 0) {
emit NoAddressesAvailable();
return false;
}
bytes32 hashBlock100 = block.blockhash(100); //Get hash of previous 100th block
bytes32 randomHash = keccak256(keccak256(hashBlock100)); //SAFETY CHECK: Increase difficulty to reverse needed hashBlock100 (in case of attack by the miners)
byte posAddr = randomHash[1]; //Check position one (to 10, maximum) of randomHash to use for the position(s) in the addresses array
byte howMany = randomHash[30]; //Check position 30 of randomHash to use for how many addresses base
uint8 posInt = (uint8(posAddr) + range * 2) % uint8(lengthAddresses()); //SAFETY CHECK: lengthAddresses() can't be greater than 256!!
uint8 howManyInt = uint8(howMany) % uint8(lengthAddresses()); //SAFETY CHECK: lengthAddresses() can't be greater than 256!!
howManyInt = howManyInt > 10 ? 10 : howManyInt; //At maximum distribute to 10 addresses
howManyInt = howManyInt < 2 ? 2 : howManyInt; //At minimum distribute to 2 addresses
address addr;
uint8 counter = 0;
uint quant = quantity / howManyInt;
do {
//Distribute to one random address:
addr = lastAddresses[posInt];
transfer(addr, quant);
posInt = (uint8(randomHash[1 + counter]) + range * 2) % uint8(lengthAddresses());
counter++;
//SAFETY CHECK: As the integer divisions are truncated (--> (quant * howManyInt) <= quantity (always) ), the following code is not needed:
/*
//we have to ensure, in case of uneven division, to just use at maximum the quantity specified by the user:
if(quantity > quant) {
quantity = quantity - quant;
}
else {
quant = quantity;
}
*/
}
while(quantity > 0 && counter < howManyInt);
return true;
}
// ------------------------------------------------------------------------
// Method will be used to set a certain number of addresses periodically. These addresses will be the ones to receive randomly the tokens when somebody makes it rain!
// The list of addresses should be gotten from the main ethereum, by checking for addresses used in the latest transactions.
// ------------------------------------------------------------------------
function setAddressesForRain(address[] memory addresses) public onlyOwner returns (bool success) {
require(addresses.length <= uint(maxAddresses) && addresses.length > 0);
lastAddresses = addresses;
firstAddress = 0;
lastAddress = int32(addresses.length) - 1;
return true;
}
// ------------------------------------------------------------------------
// Will get the Maximum of addresses to be used for making it rain
// ------------------------------------------------------------------------
function getMaxAddresses() public view returns (int32) {
return maxAddresses;
}
// ------------------------------------------------------------------------
// Will set the Maximum of addresses to be used for making it rain (Maximum of 255 Addresses)
// ------------------------------------------------------------------------
function setMaxAddresses(int32 _maxAddresses) public onlyOwner returns (bool success) {
require(_maxAddresses > 0 && _maxAddresses < 256);
maxAddresses = _maxAddresses;
return true;
}
// ------------------------------------------------------------------------
// Will get the Buy Ratio
// ------------------------------------------------------------------------
function getBuyRatio() public view returns (uint) {
return buyRatio;
}
// ------------------------------------------------------------------------
// Will set the Buy Ratio
// ------------------------------------------------------------------------
function setBuyRatio(uint ratio) public onlyOwner returns (bool success) {
require(ratio != 0);
buyRatio = ratio;
return true;
}
// ------------------------------------------------------------------------
// Will get the Sell Ratio
// ------------------------------------------------------------------------
function getSellRatio() public view returns (uint) {
return sellRatio;
}
// ------------------------------------------------------------------------
// Will set the Sell Ratio
// ------------------------------------------------------------------------
function setSellRatio(uint ratio) public onlyOwner returns (bool success) {
require(ratio != 0);
sellRatio = ratio;
return true;
}
// ------------------------------------------------------------------------
// Will set the Direct Offers Comission Ratio
// ------------------------------------------------------------------------
function setDirectOffersComissionRatio(uint ratio) public onlyOwner returns (bool success) {
require(ratio != 0);
directOffersComissionRatio = ratio;
return true;
}
// ------------------------------------------------------------------------
// Will get the Direct Offers Comission Ratio
// ------------------------------------------------------------------------
function getDirectOffersComissionRatio() public view returns (uint) {
return directOffersComissionRatio;
}
// ------------------------------------------------------------------------
// Will set the Market Comission Ratio
// ------------------------------------------------------------------------
function setMarketComissionRatio(uint ratio) public onlyOwner returns (bool success) {
require(ratio != 0);
marketComissionRatio = ratio;
return true;
}
// ------------------------------------------------------------------------
// Will get the Market Comission Ratio
// ------------------------------------------------------------------------
function getMarketComissionRatio() public view returns (uint) {
return marketComissionRatio;
}
// ------------------------------------------------------------------------
// Will set the Maximum of Market Offers
// ------------------------------------------------------------------------
function setMaxMarketOffers(int32 _maxMarketOffers) public onlyOwner returns (bool success) {
uint blackMarketOffersSortedSize = blackMarketOffersSorted.sizeOf();
if(blackMarketOffersSortedSize > uint(_maxMarketOffers)) {
int32 diff = int32(blackMarketOffersSortedSize - uint(_maxMarketOffers));
//require(diff < _maxMarketOffers);
require(diff <= int32(blackMarketOffersSortedSize)); //SAFETY CHECK (recommended because of type conversions)!
//Do the needed number of Pops to clear the market offers list if _maxMarketOffers (new) < maxMarketOffers (old)
while (diff > 0) {
uint lastOrder = blackMarketOffersSorted.pop(PREV); //Pops element from the Tail!
delete blackMarketOffersMap[lastOrder];
diff--;
}
}
maxMarketOffers = _maxMarketOffers;
//blackMarketOffers.length = maxMarketOffers;
return true;
}
// ------------------------------------------------------------------------
// Internal function to calculate the number of extra blocks needed to flush, depending on the stash to flush (the greater the load, more difficult it will be)
// ------------------------------------------------------------------------
function calculateFactorFlushDifficulty(uint stash) internal pure returns (uint extraBlocks) {
uint numBlocksToFlush = 10;
uint16 factor;
if(stash < 1000) {
factor = 1;
}
else if(stash < 5000) {
factor = 2;
}
else if(stash < 10000) {
factor = 3;
}
else if(stash < 100000) {
factor = 4;
}
else if(stash < 1000000) {
factor = 5;
}
else if(stash < 10000000) {
factor = 10;
}
else if(stash < 100000000) {
factor = 50;
}
else if(stash < 1000000000) {
factor = 500;
}
else {
factor = 5000;
}
return numBlocksToFlush * factor;
}
// ------------------------------------------------------------------------
// Throws away your stash (down the drain ;) ) immediately.
// ------------------------------------------------------------------------
function downTheDrainImmediate() internal returns (bool success) {
//Clean any flushing that it still had if possible:
toFlush[msg.sender] = 0;
//Transfer to contract all the balance:
transfer(address(0), balances[msg.sender]);
tastersReceived[msg.sender] = 0;
emit Flushed(msg.sender);
return true;
}
// ------------------------------------------------------------------------
// Throws away your stash (down the drain ;) ). It can take awhile to be completely flushed. You can send in 0.01 ether to speed up this process.
// ------------------------------------------------------------------------
function downTheDrain() public whenNotPaused payable returns (bool success) {
if(msg.value < 0.01 ether) {
//No hurry, will use default method to flush the coke (will take some time)
toFlush[msg.sender] = block.number + calculateFactorFlushDifficulty(balances[msg.sender]);
return true;
}
else return downTheDrainImmediate();
}
// ------------------------------------------------------------------------
// Checks if the dump is complete and we can flush the whole stash!
// ------------------------------------------------------------------------
function flush() public whenNotPaused returns (bool success) {
//Current block number is already greater than the limit to be flushable?
if(block.number >= toFlush[msg.sender]) {
return downTheDrainImmediate();
}
else return false;
}
// ------------------------------------------------------------------------
// Comparator used to compare priceRatios inside the LinkedList
// ------------------------------------------------------------------------
function smallerPriceComparator(uint priceNew, uint nodeNext) internal view returns (bool success) {
//When comparing ratios the smaller one will be the one with the greater ratio (cheaper price):
//return priceNew < blackMarketOffersMap[nodeNext].price;
return priceNew > blackMarketOffersMap[nodeNext].price; //If priceNew ratio is greater, it means it is a cheaper offer!
}
// ------------------------------------------------------------------------
// Put order on the blackmarket to sell a certain quantity of coke at a certain price.
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH) (for example, to get 10g for 1 ETH, the ratio should be 10000000)
// For sellers the lower the ratio the better, the more ETH the buyer will need to spend to get each token!
// - Seller must have enough balance of tokens
// ------------------------------------------------------------------------
function sellToBlackMarket(uint quantity, uint priceRatio) public whenNotPaused whenNotFlushing returns (bool success, uint numOrderCreated) {
//require(quantity <= balances[msg.sender]block.number >= toFlush[msg.sender]);
//CHeck if user has sufficient balance to do a sell offer:
if(quantity > balances[msg.sender]) {
//Seller is missing funds: Abort order:
emit OrderInsufficientBalance(msg.sender, quantity, balances[msg.sender]);
return (false, 0);
}
//Insert order in the sorted list (from cheaper to most expensive)
//Find an offer that is more expensive:
//nodeMoreExpensive =
uint nextSpot;
bool foundPosition;
uint sizeNow;
(nextSpot, foundPosition, sizeNow) = blackMarketOffersSorted.getSortedSpotByFunction(HEAD, priceRatio, NEXT, smallerPriceComparator, maxMarketOffers);
if(foundPosition) {
//Create new Sell Offer:
uint newNodeNum = ++marketOfferCounter; //SAFETY CHECK: Doesn't matter if we cycle again from MAX_INT to 0, as we have only 100 maximum offers at a time, so there will never be some overwriting of valid offers!
blackMarketOffersMap[newNodeNum].quantity = quantity;
blackMarketOffersMap[newNodeNum].price = priceRatio;
blackMarketOffersMap[newNodeNum].seller = msg.sender;
//Insert cheaper offer before nextSpot:
blackMarketOffersSorted.insert(nextSpot, newNodeNum, PREV);
if(int32(sizeNow) > maxMarketOffers) {
//Delete the tail element so we can keep the same number of max market offers:
uint lastIndex = blackMarketOffersSorted.pop(PREV); //Pops and removes last element of the list!
delete blackMarketOffersMap[lastIndex];
}
emit BlackMarketOfferAvailable(quantity, priceRatio);
return (true, newNodeNum);
}
else {
return (false, 0);
}
}
// ------------------------------------------------------------------------
// Cancel order on the blackmarket to sell a certain quantity of coke at a certain price.
// If the seller has various order with the same quantity and priceRatio, and can put parameter "continueAfterFirstMatch" to true,
// so it will continue and cancel all those black market orders.
// ------------------------------------------------------------------------
function cancelSellToBlackMarket(uint quantity, uint priceRatio, bool continueAfterFirstMatch) public whenNotPaused returns (bool success, uint numOrdersCanceled) {
//Get first node:
bool exists;
bool matchFound = false;
uint offerNodeIndex;
uint offerNodeIndexToProcess;
(exists, offerNodeIndex) = blackMarketOffersSorted.getAdjacent(HEAD, NEXT);
if(!exists)
return (false, 0); //Black Market is empty of offers!
do {
offerNodeIndexToProcess = offerNodeIndex; //Store the current index that is being processed!
(exists, offerNodeIndex) = blackMarketOffersSorted.getAdjacent(offerNodeIndex, NEXT); //Get next node
//Analyse current node, to see if it is the one to cancel:
if( blackMarketOffersMap[offerNodeIndexToProcess].seller == msg.sender
&& blackMarketOffersMap[offerNodeIndexToProcess].quantity == quantity
&& blackMarketOffersMap[offerNodeIndexToProcess].price == priceRatio) {
//Cancel current offer:
blackMarketOffersSorted.remove(offerNodeIndexToProcess);
delete blackMarketOffersMap[offerNodeIndexToProcess];
matchFound = true;
numOrdersCanceled++;
success = true;
emit BlackMarketOfferCancelled(quantity, priceRatio);
}
else {
matchFound = false;
}
}
while(offerNodeIndex != NULL && exists && (!matchFound || continueAfterFirstMatch));
return (success, numOrdersCanceled);
}
function calculateAndUpdateGains(SellOfferComplete offerThisRound) internal returns (uint) {
//Calculate values to be payed for this seller:
uint weiToBePayed = calculateEthValueFromTokens(offerThisRound.quantity, offerThisRound.price);
//Calculate fees and values to distribute:
uint fee = safeDiv(weiToBePayed, marketComissionRatio);
uint valueForSeller = safeSub(weiToBePayed, fee);
//Update change values (seller will have to retrieve his/her gains by calling method "retrieveGains" to receive the Eth)
gainsToReceive[offerThisRound.seller] = safeAdd(gainsToReceive[offerThisRound.seller], valueForSeller);
emit GainsGotten(offerThisRound.seller, valueForSeller, gainsToReceive[offerThisRound.seller]);
return weiToBePayed;
}
function matchOffer(uint quantity, uint nodeIndex, SellOfferComplete storage offer) internal returns (bool exists, uint offerNodeIndex, uint quantityRound, uint weiToBePayed, bool cleared) {
uint quantityToCheck = min(quantity, offer.quantity); //Quantity to check for this seller offer)
SellOfferComplete memory offerThisRound = offer;
bool forceRemovalOffer = false;
//Check token balance of seller:
if(balances[offerThisRound.seller] < quantityToCheck) {
//Invalid offer now, user no longer has sufficient balance
quantityToCheck = balances[offerThisRound.seller];
//Seller will no longer have balance: Clear offer from market!
forceRemovalOffer = true;
}
offerThisRound.quantity = quantityToCheck;
if(offerThisRound.quantity > 0) {
//Seller of this offer will receive his Ether:
//Calculate and update gains:
weiToBePayed = calculateAndUpdateGains(offerThisRound);
//Update current offer:
offer.quantity = safeSub(offer.quantity, offerThisRound.quantity);
//Emit event to signal an order was bought:
emit BlackMarketOfferBought(offerThisRound.quantity, offerThisRound.price, offer.quantity);
//Transfer tokens between seller and buyer:
//SAFETY CHECK: No more transactions are made to other contracts!
transferInt(offer.seller, msg.sender /* buyer */, offerThisRound.quantity, true);
}
//Keep a copy of next node:
(exists, offerNodeIndex) = blackMarketOffersSorted.getAdjacent(nodeIndex, NEXT);
//Check if current offer was completely fullfulled and remove it from market:
if(forceRemovalOffer || offer.quantity == 0) {
//Seller no longer has balance: Clear offer from market!
//Or Seller Offer was completely fulfilled
//Delete the first element so we can remove current order from the market:
uint firstIndex = blackMarketOffersSorted.pop(NEXT); //Pops and removes first element of the list!
delete blackMarketOffersMap[firstIndex];
cleared = true;
}
quantityRound = offerThisRound.quantity;
return (exists, offerNodeIndex, quantityRound, weiToBePayed, cleared);
}
// ------------------------------------------------------------------------
// Put order on the blackmarket to sell a certain quantity of coke at a certain price.
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH) (for example, to get 10g for 1 ETH, the ratio should be 10000000)
// For buyers the higher the ratio the better, the more they get!
// - Buyer must have sent enough payment for the buy he wants
// - If buyer sends more than needed, it will be available for him to get it back as change (through the retrieveChange method)
// - Gains of sellers will be available through the retrieveGains method
// ------------------------------------------------------------------------
function buyFromBlackMarket(uint quantity, uint priceRatioLimit) public payable whenNotPaused whenNotFlushing noReentrancy returns (bool success, bool partial, uint numOrdersCleared) {
numOrdersCleared = 0;
partial = false;
//Get cheapest offer on the market right now:
bool exists;
bool cleared = false;
uint offerNodeIndex;
(exists, offerNodeIndex) = blackMarketOffersSorted.getAdjacent(HEAD, NEXT);
if(!exists) {
//Abort buy from market!
revert(); //Return Eth to buyer!
//Maybe in the future, put the buyer offer in a buyer's offers list!
//TODO: IMPROVEMENTS!
}
SellOfferComplete storage offer = blackMarketOffersMap[offerNodeIndex];
uint totalToBePayedWei = 0;
uint weiToBePayedRound = 0;
uint quantityRound = 0;
//When comparing ratios the smaller one will be the one with the greater ratio (cheaper price):
//if(offer.price > priceRatioLimit) {
if(offer.price < priceRatioLimit) {
//Abort buy from market! Not one sell offer is cheaper than the priceRatioLimit
//BlackMarketNoOfferForPrice(priceRatioLimit);
//return (false, 0);
revert(); //Return Eth to buyer!
//Maybe in the future, put the buyer offer in a buyer's offers list!
//TODO: IMPROVEMENTS!
}
bool abort = false;
//Cycle through market seller offers:
do {
(exists /* Exists next offer to match */,
offerNodeIndex, /* Node index for Next Offer */
quantityRound, /* Quantity that was matched in this round */
weiToBePayedRound, /* Wei that was used to pay for this round */
cleared /* Offer was completely fulfilled and was cleared! */
) = matchOffer(quantity, offerNodeIndex, offer);
if(cleared) {
numOrdersCleared++;
}
//Update total to be payed (in Wei):
totalToBePayedWei = safeAdd(totalToBePayedWei, weiToBePayedRound);
//Update quantity (still missing to be satisfied):
quantity = safeSub(quantity, quantityRound);
//Check if buyer send enough balance to buy the orders:
if(totalToBePayedWei > msg.value) {
emit OrderInsufficientPayment(msg.sender, totalToBePayedWei, msg.value);
//Abort transaction!:
revert(); //Revert transaction, so Eth send are not transferred, and go back to user!
//TODO: IMPROVEMENTS!
//TODO: Improvements to allow a partial buy, if not possible to buy all!
}
//Confirm if next node exists:
if(offerNodeIndex != NULL) {
//Get Next Node (More Info):
offer = blackMarketOffersMap[offerNodeIndex];
//Check if next order is above the priceRatioLimit set by the buyer:
//When comparing ratios the smaller one will be the one with the greater ratio (cheaper price):
//if(offer.price > priceRatioLimit) {
if(offer.price < priceRatioLimit) {
//Abort buying more from the seller's market:
abort = true;
partial = true; //Partial buy order done! (no sufficient seller offer's below the priceRatioLimit)
//Maybe in the future, put the buyer offer in a buyer's offers list!
//TODO: IMPROVEMENTS!
}
}
else {
//Abort buying more from the seller's market (the end was reached!):
abort = true;
}
}
while (exists && quantity > 0 && !abort);
//End Cycle through orders!
//Final operations after checking all orders:
if(totalToBePayedWei < msg.value) {
//Give change back to the buyer:
//Return change to the buyer (sender of the message in this case)
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value - totalToBePayedWei); //SAFETY CHECK: No need to use safeSub, as we already know that "msg.value" > "totalToBePayedWei"!
emit ChangeToReceiveGotten(msg.sender, msg.value - totalToBePayedWei, changeToReturn[msg.sender]);
}
return (true, partial, numOrdersCleared);
}
// ------------------------------------------------------------------------
// Gets the list of orders on the black market (ordered by cheapest to expensive).
// ------------------------------------------------------------------------
function getSellOrdersBlackMarket() public view returns (uint[] memory r) {
r = new uint[](blackMarketOffersSorted.sizeOf());
bool exists;
uint prev;
uint elem;
(exists, prev, elem) = blackMarketOffersSorted.getNode(HEAD);
if(exists) {
uint size = blackMarketOffersSorted.sizeOf();
for (uint i = 0; i < size; i++) {
r[i] = elem;
(exists, elem) = blackMarketOffersSorted.getAdjacent(elem, NEXT);
}
}
}
// ------------------------------------------------------------------------
// Gets the list of orders on the black market (ordered by cheapest to expensive).
// WARNING: Not Supported by Remix or Web3!! (Structure Array returns)
// ------------------------------------------------------------------------
/*
function getSellOrdersBlackMarketComplete() public view returns (SellOffer[] memory r) {
r = new SellOffer[](blackMarketOffersSorted.sizeOf());
bool exists;
uint prev;
uint elem;
(exists, prev, elem) = blackMarketOffersSorted.getNode(HEAD);
if(exists) {
for (uint i = 0; i < blackMarketOffersSorted.sizeOf(); i++) {
SellOfferComplete storage offer = blackMarketOffersMap[elem];
r[i].quantity = offer.quantity;
r[i].price = offer.price;
(exists, elem) = blackMarketOffersSorted.getAdjacent(elem, NEXT);
}
}
}
*/
function getSellOrdersBlackMarketComplete() public view returns (uint[] memory quantities, uint[] memory prices) {
quantities = new uint[](blackMarketOffersSorted.sizeOf());
prices = new uint[](blackMarketOffersSorted.sizeOf());
bool exists;
uint prev;
uint elem;
(exists, prev, elem) = blackMarketOffersSorted.getNode(HEAD);
if(exists) {
uint size = blackMarketOffersSorted.sizeOf();
for (uint i = 0; i < size; i++) {
SellOfferComplete storage offer = blackMarketOffersMap[elem];
quantities[i] = offer.quantity;
prices[i] = offer.price;
//Get next element:
(exists, elem) = blackMarketOffersSorted.getAdjacent(elem, NEXT);
}
}
}
function getMySellOrdersBlackMarketComplete() public view returns (uint[] memory quantities, uint[] memory prices) {
quantities = new uint[](blackMarketOffersSorted.sizeOf());
prices = new uint[](blackMarketOffersSorted.sizeOf());
bool exists;
uint prev;
uint elem;
(exists, prev, elem) = blackMarketOffersSorted.getNode(HEAD);
if(exists) {
uint size = blackMarketOffersSorted.sizeOf();
uint j = 0;
for (uint i = 0; i < size; i++) {
SellOfferComplete storage offer = blackMarketOffersMap[elem];
if(offer.seller == msg.sender) {
quantities[j] = offer.quantity;
prices[j] = offer.price;
j++;
}
//Get next element:
(exists, elem) = blackMarketOffersSorted.getAdjacent(elem, NEXT);
}
}
//quantities.length = j; //Memory Arrays can't be returned with dynamic size, we have to create arrays with a fixed size to be returned!
//prices.length = j;
}
// ------------------------------------------------------------------------
// Puts an offer on the market to a specific user (if an offer from the same seller to the same consumer already exists, the latest offer will replace it)
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function sellToConsumer(address consumer, uint quantity, uint priceRatio) public whenNotPaused whenNotFlushing returns (bool success) {
require(consumer != address(0) && quantity > 0 && priceRatio > 0);
//Mark offer to sell to consumer on registry:
SellOffer storage offer = directOffers[msg.sender][consumer];
offer.quantity = quantity;
offer.price = priceRatio;
emit DirectOfferAvailable(msg.sender, consumer, offer.quantity, offer.price);
return true;
}
// ------------------------------------------------------------------------
// Puts an offer on the market to a specific user
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function cancelSellToConsumer(address consumer) public whenNotPaused returns (bool success) {
//Check if order exists with the correct values:
SellOffer memory sellOffer = directOffers[msg.sender][consumer];
if(sellOffer.quantity > 0 || sellOffer.price > 0) {
//We found matching sell to consumer, delete it to cancel it!
delete directOffers[msg.sender][consumer];
emit DirectOfferCancelled(msg.sender, consumer, sellOffer.quantity, sellOffer.price);
return true;
}
return false;
}
// ------------------------------------------------------------------------
// Checks a seller offer from the seller side
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function checkMySellerOffer(address consumer) public view returns (uint quantity, uint priceRatio, uint totalWeiCost) {
quantity = directOffers[msg.sender][consumer].quantity;
priceRatio = directOffers[msg.sender][consumer].price;
totalWeiCost = calculateEthValueFromTokens(quantity, priceRatio); //Value to be payed by the buyer (in Wei)
}
// ------------------------------------------------------------------------
// Checks a seller offer to the user. Method used by the buyer to check an offer (direct offer) from a seller to him/her and to see
// how much he/she will have to pay for it (in Wei).
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function checkSellerOffer(address seller) public view returns (uint quantity, uint priceRatio, uint totalWeiCost) {
quantity = directOffers[seller][msg.sender].quantity;
priceRatio = directOffers[seller][msg.sender].price;
totalWeiCost = calculateEthValueFromTokens(quantity, priceRatio); //Value to be payed by the buyer (in Wei)
}
// ------------------------------------------------------------------------
// Buys from a trusted dealer.
// The buyer has to send the needed Ether to pay for the quantity of material specified at that priceRatio (the buyer can use
// checkSellerOffer(), and input the seller address to know the quantity and priceRatio specified and also, of course, how much Ether in Wei
// he/she will have to pay for it).
// The price ratio is how much micrograms (ug) of material (tokens) the buyer will get per ETH (ug/ETH)
// ------------------------------------------------------------------------
function buyFromTrusterDealer(address dealer, uint quantity, uint priceRatio) public payable noReentrancy whenNotPaused returns (bool success) {
//Check up on offer:
require(directOffers[dealer][msg.sender].quantity > 0 && directOffers[dealer][msg.sender].price > 0); //Offer exists?
if(quantity > directOffers[dealer][msg.sender].quantity) {
emit OrderQuantityMismatch(dealer, directOffers[dealer][msg.sender].quantity, quantity);
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value); //Operation aborted: The buyer can get its ether back by using retrieveChange().
emit ChangeToReceiveGotten(msg.sender, msg.value, changeToReturn[msg.sender]);
return false;
}
if(directOffers[dealer][msg.sender].price != priceRatio) {
emit OrderPriceMismatch(dealer, directOffers[dealer][msg.sender].price, priceRatio);
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value); //Operation aborted: The buyer can get its ether back by using retrieveChange().
emit ChangeToReceiveGotten(msg.sender, msg.value, changeToReturn[msg.sender]);
return false;
}
//Offer valid, start buying proccess:
//Get values to be payed:
uint weiToBePayed = calculateEthValueFromTokens(quantity, priceRatio);
//Check eth payment from buyer:
if(msg.value < weiToBePayed) {
emit OrderInsufficientPayment(msg.sender, weiToBePayed, msg.value);
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value); //Operation aborted: The buyer can get its ether back by using retrieveChange().
emit ChangeToReceiveGotten(msg.sender, msg.value, changeToReturn[msg.sender]);
return false;
}
//Check balance from seller:
if(quantity > balances[dealer]) {
//Seller is missing funds: Abort order:
emit OrderInsufficientBalance(dealer, quantity, balances[dealer]);
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], msg.value); //Operation aborted: The buyer can get its ether back by using retrieveChange().
emit ChangeToReceiveGotten(msg.sender, msg.value, changeToReturn[msg.sender]);
return false;
}
//Update balances of seller/buyer:
balances[dealer] = balances[dealer] - quantity; //SAFETY CHECK: No need to use safeSub, as we already know that "balances[dealer]" >= "quantity"!
balances[msg.sender] = safeAdd(balances[msg.sender], quantity);
emit Transfer(dealer, msg.sender, quantity);
//Update direct offers registry:
if(quantity < directOffers[dealer][msg.sender].quantity) {
//SAFETY CHECK: No need to use safeSub, as we already know that "directOffers[dealer][msg.sender].quantity" > "quantity"!
directOffers[dealer][msg.sender].quantity = directOffers[dealer][msg.sender].quantity - quantity;
}
else {
//Remove offer from registry (order completely filled)
delete directOffers[dealer][msg.sender];
}
//Receive payment from one user and send it to another, minus the comission:
//Calculate fees and values to distribute:
uint fee = safeDiv(weiToBePayed, directOffersComissionRatio);
uint valueForSeller = safeSub(weiToBePayed, fee);
//SAFETY CHECK: Possible Denial of Service, by putting a fallback function impossible to run: No problem! As this is a direct offer between two users, if it doesn't work the first time, the user can just ignore the offer!
//SAFETY CHECK: No Reentrancy possible: Modifier active!
//SAFETY CHECK: Balances are all updated before transfer, and offer is removed/updated too! Only change is updated later, which is good as user can only retrieve the funds after this operations finishes with success!
dealer.transfer(valueForSeller);
//Set change to the buyer if he sent extra eth:
uint changeToGive = safeSub(msg.value, weiToBePayed);
if(changeToGive > 0) {
//Update change values (user will have to retrieve the change calling method "retrieveChange" to receive the Eth)
changeToReturn[msg.sender] = safeAdd(changeToReturn[msg.sender], changeToGive);
emit ChangeToReceiveGotten(msg.sender, changeToGive, changeToReturn[msg.sender]);
}
return true;
}
/****************************************************************************
// Message board management functions
//***************************************************************************/
// ------------------------------------------------------------------------
// Comparator used to compare Eth payed for a message inside the top messages LinkedList
// ------------------------------------------------------------------------
function greaterPriceMsgComparator(uint valuePayedNew, uint nodeNext) internal view returns (bool success) {
return valuePayedNew > (topMessagesMap[nodeNext].valuePayed);
}
// ------------------------------------------------------------------------
// Place a message in the Message Board
// The latest messages will be shown on the message board (usually it should display the 100 latest messages)
// User can also spend some wei to put the message in the top 10/20 of messages, ordered by the most payed to the least payed.
// ------------------------------------------------------------------------
function placeMessage(string message, bool anon) public payable whenNotPaused returns (bool success, uint numMsgTop) {
uint msgSize = bytes(message).length;
if(msgSize > maxCharactersMessage) { //Check number of bytes of message
//Message is bigger than maximum allowed: Reject message!
emit ExceededMaximumMessageSize(msgSize, maxCharactersMessage);
if(msg.value > 0) { //We have Eth to return, so we will return it!
revert(); //Cancel transaction and Return Eth!
}
return (false, 0);
}
//Insert message in the sorted list (from most to least expensive) of top messages
//If the value payed is enough for it to reach the top
//Find an offer that is cheaper:
//nodeLessExpensive =
uint nextSpot;
bool foundPosition;
uint sizeNow;
(nextSpot, foundPosition, sizeNow) = topMessagesSorted.getSortedSpotByFunction(HEAD, msg.value, NEXT, greaterPriceMsgComparator, maxMessagesTop);
if(foundPosition) {
//Create new Message:
uint newNodeNum = ++topMessagesCounter; //SAFETY CHECK: Doesn't matter if we cycle again from MAX_INT to 0, as we have only 10/20/100 maximum messages at a time, so there will never be some overwriting of valid offers!
topMessagesMap[newNodeNum].valuePayed = msg.value;
topMessagesMap[newNodeNum].msg = message;
topMessagesMap[newNodeNum].from = anon ? address(0) : msg.sender;
//Insert more expensive message before nextSpot:
topMessagesSorted.insert(nextSpot, newNodeNum, PREV);
if(int32(sizeNow) > maxMessagesTop) {
//Delete the tail element so we can keep the same number of max top messages:
uint lastIndex = topMessagesSorted.pop(PREV); //Pops and removes last element of the list!
delete topMessagesMap[lastIndex];
}
}
//Place message in the most recent messages (Will always be put here, even if the value payed is zero! Will only be ordered by time, from older to most recent):
insertMessage(message, anon);
emit NewMessageAvailable(anon ? address(0) : msg.sender, message);
return (true, newNodeNum);
}
function lengthMessages() internal view returns (uint) {
return (firstMsgGlobal > 0) ? messages.length : uint(lastMsgGlobal + 1);
}
function insertMessage(string message, bool anon) internal {
Message memory newMsg;
bool insertInLastPos = false;
newMsg.valuePayed = msg.value;
newMsg.msg = message;
newMsg.from = anon ? address(0) : msg.sender;
if(((lastMsgGlobal + 1) >= int32(messages.length) && int32(messages.length) < maxMessagesGlobal)) {
//Still have space in the messages array, add new message at the end:
messages.push(newMsg);
//lastMsgGlobal++;
} else {
//Messages array is full, start rotating through it:
insertInLastPos = true;
}
//Rotating indexes in case we reach the end of the array!
uint sizeMessages = lengthMessages(); //lengthMessages() depends on lastMsgGlobal, se we have to keep a temporary copy first!
lastMsgGlobal = (lastMsgGlobal + 1) % maxMessagesGlobal;
if(lastMsgGlobal <= firstMsgGlobal && sizeMessages > 0) {
firstMsgGlobal = (firstMsgGlobal + 1) % maxMessagesGlobal;
}
if(insertInLastPos) {
messages[uint(lastMsgGlobal)] = newMsg;
}
}
function strConcat(string _a, string _b, string _c) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory ab = new string(_ba.length + _bb.length + _bc.length);
bytes memory ba = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) ba[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) ba[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) ba[k++] = _bc[i];
return string(ba);
}
// ------------------------------------------------------------------------
// Place a message in the Message Board
// The latest messages will be shown on the message board (usually it should display the 100 latest messages)
// User can also spend some wei to put the message in the top 10/20 of messages, ordered by the most payed to the least payed.
// ------------------------------------------------------------------------
function getMessages() public view returns (string memory r) {
uint countMsg = lengthMessages(); //Take into account if messages was reset, and no new messages have been inserted until now!
uint indexMsg = uint(firstMsgGlobal);
bool first = true;
while(countMsg > 0) {
if(first) {
r = messages[indexMsg].msg;
first = false;
}
else {
r = strConcat(r, " <||> ", messages[indexMsg].msg);
}
indexMsg = (indexMsg + 1) % uint(maxMessagesGlobal);
countMsg--;
}
return r;
}
// ------------------------------------------------------------------------
// Will set the Maximum of Global Messages
// ------------------------------------------------------------------------
function setMaxMessagesGlobal(int32 _maxMessagesGlobal) public onlyOwner returns (bool success) {
if(_maxMessagesGlobal < maxMessagesGlobal) {
//New value will be shorter than old value: reset values:
//messages.clear(); //No need to clear the array completely (costs gas!): Just reinitialize the pointers!
//lastMsgGlobal = firstMsgGlobal > 0 ? int32(messages.length) - 1 : lastMsgGlobal; //The last position will specify the real size of the array, that is, until the firstMsgGlobal is greater than zero, at that time we know the array is full, so the real size is the size of the complete array!
lastMsgGlobal = int32(lengthMessages()) - 1; //The last position will specify the real size of the array, that is, until the firstMsgGlobal is greater than zero, at that time we know the array is full, so the real size is the size of the complete array!
if(lastMsgGlobal != -1 && lastMsgGlobal > (int32(_maxMessagesGlobal) - 1)) {
lastMsgGlobal = int32(_maxMessagesGlobal) - 1;
}
firstMsgGlobal = 0;
messages.length = uint(_maxMessagesGlobal);
}
maxMessagesGlobal = _maxMessagesGlobal;
return true;
}
// ------------------------------------------------------------------------
// Will set the Maximum of Top Messages (usually Top 10 / 20)
// ------------------------------------------------------------------------
function setMaxMessagesTop(int32 _maxMessagesTop) public onlyOwner returns (bool success) {
uint topMessagesSortedSize = topMessagesSorted.sizeOf();
if(topMessagesSortedSize > uint(_maxMessagesTop)) {
int32 diff = int32(topMessagesSortedSize - uint(_maxMessagesTop));
require(diff <= int32(topMessagesSortedSize)); //SAFETY CHECK (recommended because of type conversions)!
//Do the needed number of Pops to clear the top message list if _maxMessagesTop (new) < maxMessagesTop (old)
while (diff > 0) {
uint lastMsg = topMessagesSorted.pop(PREV); //Pops element from the Tail!
delete topMessagesMap[lastMsg];
diff--;
}
}
maxMessagesTop = _maxMessagesTop;
return true;
}
// ------------------------------------------------------------------------
// Gets the list of top 10 messages (ordered by most payed to least payed).
// ------------------------------------------------------------------------
function getTop10Messages() public view returns (string memory r) {
bool exists;
uint prev;
uint elem;
bool first = true;
(exists, prev, elem) = topMessagesSorted.getNode(HEAD);
if(exists) {
uint size = min(topMessagesSorted.sizeOf(), 10);
for (uint i = 0; i < size; i++) {
if(first) {
r = topMessagesMap[elem].msg;
first = false;
}
else {
r = strConcat(r, " <||> ", topMessagesMap[elem].msg);
}
(exists, elem) = topMessagesSorted.getAdjacent(elem, NEXT);
}
}
return r;
}
// ------------------------------------------------------------------------
// Gets the list of top 11 to 20 messages (ordered by most payed to least payed).
// ------------------------------------------------------------------------
function getTop11_20Messages() public view returns (string memory r) {
bool exists;
uint prev;
uint elem;
bool first = true;
(exists, prev, elem) = topMessagesSorted.getNode(HEAD);
if(exists) {
uint size = min(topMessagesSorted.sizeOf(), uint(maxMessagesTop));
for (uint i = 0; i < size; i++) {
if(i >= 10) {
if(first) {
r = topMessagesMap[elem].msg;
first = false;
}
else {
r = strConcat(r, " <||> ", topMessagesMap[elem].msg);
}
}
(exists, elem) = topMessagesSorted.getAdjacent(elem, NEXT);
}
}
return r;
}
// ------------------------------------------------------------------------
// Will set the Maximum Characters each message can have
// ------------------------------------------------------------------------
function setMessageMaxCharacters(uint _maxCharactersMessage) public onlyOwner returns (bool success) {
maxCharactersMessage = _maxCharactersMessage;
return true;
}
// ------------------------------------------------------------------------
// Get the Maximum Characters each message can have
// ------------------------------------------------------------------------
function getMessageMaxCharacters() public view returns (uint maxChars) {
return maxCharactersMessage;
}
// ------------------------------------------------------------------------
// Default function
// ------------------------------------------------------------------------
function () public payable {
buyCoke();
}
} | ------------------------------------------------------------------------ Internal function to calculate the number of extra blocks needed to flush, depending on the stash to flush (the greater the load, more difficult it will be) ------------------------------------------------------------------------ | function calculateFactorFlushDifficulty(uint stash) internal pure returns (uint extraBlocks) {
uint numBlocksToFlush = 10;
uint16 factor;
if(stash < 1000) {
factor = 1;
}
else if(stash < 5000) {
factor = 2;
}
else if(stash < 10000) {
factor = 3;
}
else if(stash < 100000) {
factor = 4;
}
else if(stash < 1000000) {
factor = 5;
}
else if(stash < 10000000) {
factor = 10;
}
else if(stash < 100000000) {
factor = 50;
}
else if(stash < 1000000000) {
factor = 500;
}
else {
factor = 5000;
}
return numBlocksToFlush * factor;
}
| 620,737 | [
1,
29461,
3186,
445,
358,
4604,
326,
1300,
434,
2870,
4398,
3577,
358,
3663,
16,
8353,
603,
326,
23017,
358,
3663,
261,
5787,
6802,
326,
1262,
16,
1898,
3122,
17551,
518,
903,
506,
13,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
4604,
6837,
8207,
5938,
21934,
12,
11890,
23017,
13,
2713,
16618,
1135,
261,
11890,
2870,
6450,
13,
288,
203,
3639,
2254,
818,
6450,
774,
8207,
273,
1728,
31,
203,
3639,
2254,
2313,
5578,
31,
203,
3639,
309,
12,
25915,
411,
4336,
13,
288,
203,
5411,
5578,
273,
404,
31,
203,
3639,
289,
203,
3639,
469,
309,
12,
25915,
411,
20190,
13,
288,
203,
5411,
5578,
273,
576,
31,
203,
3639,
289,
203,
3639,
469,
309,
12,
25915,
411,
12619,
13,
288,
203,
5411,
5578,
273,
890,
31,
203,
3639,
289,
203,
3639,
469,
309,
12,
25915,
411,
25259,
13,
288,
203,
5411,
5578,
273,
1059,
31,
203,
3639,
289,
203,
3639,
469,
309,
12,
25915,
411,
15088,
13,
288,
203,
5411,
5578,
273,
1381,
31,
203,
3639,
289,
203,
3639,
469,
309,
12,
25915,
411,
2130,
11706,
13,
288,
203,
5411,
5578,
273,
1728,
31,
203,
3639,
289,
203,
3639,
469,
309,
12,
25915,
411,
2130,
9449,
13,
288,
203,
5411,
5578,
273,
6437,
31,
203,
3639,
289,
203,
3639,
469,
309,
12,
25915,
411,
15088,
3784,
13,
288,
203,
5411,
5578,
273,
6604,
31,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
5578,
273,
20190,
31,
203,
3639,
289,
203,
3639,
327,
818,
6450,
774,
8207,
380,
5578,
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
] |
./full_match/5/0x321A7e7626D904545D5Af3D2a2625694554932f1/sources/StakingContract.sol | total tokens staked | uint256 private _totalCurrentlyStaked;
| 1,878,026 | [
1,
4963,
2430,
384,
9477,
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,
2254,
5034,
3238,
389,
4963,
3935,
715,
510,
9477,
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
] |
./full_match/80001/0x36996711A972DE3a838b858a73589C8488a6F759/sources/project_/contracts/Distribution.sol | uint256 uplineId, require(amount == 70 , "amount must be at least 70"); | function register(
uint256 amount,
address userAddress,
uint256 sponserId,
uint256[] calldata level,
uint256[] calldata binary
) external {
require(registered[msg.sender] == false,"User already registered");
require(P2PToken.balanceOf(msg.sender) >= amount, "Not Enough Balance");
require(
P2PToken.allowance(msg.sender, address(this)) >= amount,
"Allowance too low"
);
SafeERC20Upgradeable.safeTransferFrom(
P2PToken,
msg.sender,
address(this),
amount
);
user_data[userId] = Users(userId, msg.sender,sponserId,0,0);
amount = burnToken(amount);
amount = fundTokens(amount);
address sponser= user_data[sponserId].WalletAddress;
if(sponser == address(0)){
sponser = FundingWallet;
}
uint256 remainingDDAmount = DirectDistribution(sponser, amount);
uint256 remainingBDAmount = BinaryDistribution(binary,amount);
uint256 remainingLDAmount =LevelDistribution(level,amount);
uint256 remainingAmount = amount - (remainingBDAmount + remainingDDAmount +remainingLDAmount);
if(remainingAmount> 0){
SafeERC20Upgradeable.safeTransfer(P2PToken, FundingWallet,remainingAmount );
}
}
| 5,670,386 | [
1,
11890,
5034,
582,
412,
558,
548,
16,
2583,
12,
8949,
422,
16647,
269,
315,
8949,
1297,
506,
622,
4520,
16647,
8863,
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
] | [
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,
0
] | [
1,
565,
445,
1744,
12,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
729,
1887,
16,
203,
540,
203,
3639,
2254,
5034,
272,
500,
550,
548,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
1801,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
3112,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
14327,
63,
3576,
18,
15330,
65,
422,
629,
10837,
1299,
1818,
4104,
8863,
203,
3639,
2583,
12,
52,
22,
52,
1345,
18,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
3844,
16,
315,
1248,
1374,
4966,
30918,
8863,
203,
3639,
2583,
12,
203,
5411,
453,
22,
52,
1345,
18,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3719,
1545,
3844,
16,
203,
5411,
315,
7009,
1359,
4885,
4587,
6,
203,
3639,
11272,
203,
540,
203,
3639,
14060,
654,
39,
3462,
10784,
429,
18,
4626,
5912,
1265,
12,
203,
5411,
453,
22,
52,
1345,
16,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
3844,
203,
3639,
11272,
203,
1355,
67,
892,
63,
18991,
65,
273,
12109,
12,
18991,
16,
1234,
18,
15330,
16,
87,
500,
550,
548,
16,
20,
16,
20,
1769,
203,
8949,
273,
18305,
1345,
12,
8949,
1769,
203,
8949,
273,
284,
1074,
5157,
12,
8949,
1769,
203,
2867,
272,
500,
550,
33,
729,
67,
892,
63,
87,
500,
550,
548,
8009,
16936,
1887,
31,
203,
430,
12,
87,
500,
550,
225,
422,
1758,
12,
20,
3719,
95,
203,
565,
272,
500,
550,
273,
478,
14351,
16936,
31,
203,
97,
203,
11890,
2
] |
pragma solidity ^0.5.0;
/// @title Simple wallet
/// @author Tonlabs
contract Wallet {
/*
* Storage
*/
uint256 owner;
address public subscription;
/*
Exception codes:
100 - message sender is not a wallet owner.
101 - limit is overrun.
102 - invalid transfer value.
103 - destination address is zero.
*/
/*
* Runtime functions
*/
function tvm_sender_pubkey() private view returns (uint256) {}
function tvm_logstr(bytes32 logstr) private view {}
function tvm_transfer(address payable addr, uint128 value, bool bounce, uint16 flags) private {}
function tvm_accept() private {}
modifier checkOwnerAndAccept {
require(tvm_sender_pubkey() == owner, 100);
tvm_logstr("mod_accept");
tvm_accept();
_;
}
/*
* Public functions
*/
/// @dev Contract constructor.
constructor() public {
//TODO: tvm_accept();
owner = tvm_sender_pubkey();
}
/// @dev Allows to transfer grams to destination account.
/// @param dest Transfer target address.
/// @param value Nanograms value to transfer.
function sendTransaction(address payable dest, uint128 value, bool bounce) public checkOwnerAndAccept {
tvm_logstr("sendTrans");
require(value > 0 && value < address(this).balance, 102);
tvm_logstr("func_accept");
tvm_accept();
tvm_transfer(dest, value, bounce, 0);
}
} | Storage// Runtime functions/ | function tvm_sender_pubkey() private view returns (uint256) {}
| 12,541,542 | [
1,
3245,
759,
2509,
4186,
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,
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,
565,
445,
268,
3489,
67,
15330,
67,
23428,
1435,
3238,
1476,
1135,
261,
11890,
5034,
13,
2618,
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
] |
/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title SocialMedia
/// @notice SocialMedia content creation and voting
/// @dev This contract keeps track of all the posts created by registered users
contract SocialMedia is
Initializable,
PausableUpgradeable,
AccessControlUpgradeable,
UUPSUpgradeable,
ERC721URIStorageUpgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _idCounter;
IERC20Upgradeable public token;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
uint256 private upVoteThreshold;
uint256 private downVoteThreshold;
uint256 private numberOfExcuses;
uint256 private suspensionPeriod;
enum UserStatus {
NotActive,
banned,
Active,
Suspend
}
struct User {
uint256 userId;
address userAddress;
string profilePic;
string Alias;
UserStatus status;
}
struct Post {
uint256 id;
uint256 createDate;
bool visible;
address creator;
string description;
string content;
}
struct Vote {
uint256 postId;
uint256 upVote;
uint256 downVote;
}
struct Violation {
uint256[] postIds;
uint256 count;
address postCreator;
}
mapping(string => bool) private userAlias;
mapping(uint256 => User) public userById;
mapping(address => User) userDetails;
mapping(address => User) userByAddress;
Post[] private posts;
mapping(uint256 => Post) postById;
mapping(address => Post[]) userPosts;
mapping(uint256 => Vote) voteMap;
mapping(address => Violation) postViolation;
mapping(uint256 => uint256) currentPrice;
event UserAdded(uint256, address);
/// @notice Emitted when the new post is created
/// @param postId The unique identifier of post
/// @param createDate The date of post creation
/// @param creator The address of post creator
/// @param description The description of the post
/// @param contentUri The IPFS content uri
event PostAdded(
uint256 indexed postId,
uint256 indexed createDate,
address indexed creator,
string description,
string contentUri
);
/// @notice Emitted when any post is voted
/// @param postId The unique identifier of post
/// @param upVote The kind of vote, true = upVote, false = downVote
/// @param voter The address of the voter
event PostVote(uint256 indexed postId, bool upVote, address indexed voter);
/// @notice Emitted when any post is reported for violation
/// @param postIds The post ids that are considered violated
/// @param count The counter tracking the number of violations by user
/// @param suspensionDays The number of days user is suspended
/// @param banned The flag represents if the user is banned
/// @param postCreator The address of the post(s) creator
event PostViolation(
uint256[] postIds,
uint256 indexed count,
uint256 suspensionDays,
bool banned,
address indexed postCreator
);
modifier onlyRegisteredUser(address _userAddress) {
User memory details = userDetails[_userAddress];
require (details.status == UserStatus.Active,"User not registered yet");
_;
}
/// @notice The starting point of the contract, which defines the initial values
/// @dev This is an upgradeable contract, DO NOT have constructor, and use this function for
/// initialization of this and inheriting contracts
function initialize(IERC20Upgradeable _token) public initializer {
token = _token;
__ERC721_init("NonFungibleToken", "NFT");
__Pausable_init();
__AccessControl_init();
__UUPSUpgradeable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(PAUSER_ROLE, msg.sender);
_setupRole(UPGRADER_ROLE, msg.sender);
upVoteThreshold = 25;
downVoteThreshold = 5;
numberOfExcuses = 1;
suspensionPeriod = 7;
}
/// @inheritdoc UUPSUpgradeable
/// @dev The contract upgrade authorization handler. Only the users with role 'UPGRADER_ROLE' are allowed to upgrade the contract
/// @param newImplementation The address of the new implementation contract
function _authorizeUpgrade(address newImplementation)
internal
override
onlyRole(UPGRADER_ROLE)
{}
/// @notice Called by owner to pause, transitons the contract to stopped state
/// @dev This function can be accessed by the user with role PAUSER_ROLE
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
/// @notice Called by owner to unpause, transitons the contract back to normal state
/// @dev This function can be accessed by the user with role PAUSER_ROLE
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
/// @notice Function to get the down vote theshold
function getDownVoteThreshold() public view returns (uint256) {
return downVoteThreshold;
}
/// @notice Function to set down vote threshold
/// @dev This function can be accessed by the user with role ADMIN
function setDownVoteThreshold(uint256 _limit)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
downVoteThreshold = _limit;
}
/// @notice Function to get the number of excuses before the user is permanently banned
function getNumberOfExcuses() public view returns (uint256) {
return numberOfExcuses;
}
/// @notice Function to set number of excuses for post violations
/// @dev This function can be accessed by the user with role ADMIN
function setNumberOfExcuses(uint256 _excuses)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
numberOfExcuses = _excuses;
}
/// @notice Function to get the suspension period for user incase of violation
function getSuspensionPeriod() public view returns (uint256) {
return suspensionPeriod;
}
/// @notice Function to set the suspension period in days for each post violation
/// @dev This function can be accessed by the user with role ADMIN
function setSuspensionPeriod(uint256 _duration)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
suspensionPeriod = _duration;
}
/// @dev Post mappings to maintain
function postOperations(Post memory post) internal {
posts.push(post);
userPosts[msg.sender].push(post);
postById[post.id] = post;
}
/// @dev Increment and get the counter, which is used as the unique identifier for post
/// @return The unique identifier
function incrementAndGet() internal returns (uint256) {
_idCounter.increment();
return _idCounter.current();
}
//*************************************RegisterUsers**************************************************//
/// @notice Emitted when any post is reported for violation
/// @param _profilePic Profile image of user, will be stored on ipfs
/// @param _alias Alias here is for unique user name
function RegisterUsers(string memory _profilePic, string memory _alias)
external
{
bool isUser = isUserExists(msg.sender);
require(!isUser, "User already registered");
require(!userAlias[_alias], "Not avaliable");
userAlias[_alias] = true;
uint256 userId = incrementAndGet();
User memory users = User(
userId, msg.sender, _profilePic, _alias, UserStatus.Active
);
userDetails[msg.sender]=users;
userById[users.userId] = users;
emit UserAdded(userId, msg.sender);
}
/// @notice Check whethe user exist or not, return boolean value
/// @param _userAddress address of the user
function isUserExists(address _userAddress) public view returns (bool) {
User memory details = userDetails[_userAddress];
if (details.status == UserStatus.Active) return (true);
return (false);
}
/// @notice Allows user to delete their info
function deleteUsers() public onlyRegisteredUser(msg.sender) {
delete userDetails[msg.sender];
// userAlias[userDetails[msg.sender].Alias=false;
}
//*************************************CreatePost**************************************************//
/// @notice Create a post with any multimedia and description. The multimedia should be stored in external storage and the record pointer to be used
/// @dev Require a valid and not empty multimedia uri pointer. Emits PostAdded event.
/// @param _description The description of the uploaded multimedia
/// @param _contentUri The uri of the multimedia record captured in external storage
function createPost(string memory _description, string memory _contentUri)
external onlyRegisteredUser(msg.sender)
{
require(bytes(_contentUri).length > 0, "Empty content uri");
uint256 postId = incrementAndGet();
Post memory post = Post(
postId,
block.timestamp,
true,
msg.sender,
_description,
_contentUri
);
postOperations(post);
emit PostAdded(
postId,
block.timestamp,
msg.sender,
_description,
_contentUri
);
}
/// @notice Fetch the post record by its unique identifier
/// @param _id The unique identifier of the post
/// @return The post record
function getPostById(uint256 _id) external onlyRegisteredUser(msg.sender) view returns (Post memory) {
return postById[_id];
}
/// @notice Fetch all the post records created by user
/// @param _user The address of the user to fetch the post records
/// @return The list of post records
function getPostsByUser(address _user)
external
view
returns (Post[] memory)
{
return userPosts[_user];
}
/// @notice Fetch all the posts created accross users
/// @return The list of post records
function getAllPosts() external onlyRegisteredUser(msg.sender) view returns (Post[] memory) {
return posts;
}
//*************************************VotingPost**************************************************//
/// @notice Right to up vote or down vote any posts.
/// @dev The storage vote instance is matched on identifier and updated with the vote. Emits PostVote event
/// @param _postId The unique identifier of post
/// @param _upVote True to upVote, false to downVote
function vote(uint256 _postId, bool _upVote) external onlyRegisteredUser(msg.sender){
Vote storage voteInstance = voteMap[_postId];
voteInstance.postId = _postId;
if (_upVote) voteInstance.upVote += 1;
else voteInstance.downVote += 1;
emit PostVote(_postId, _upVote, msg.sender);
}
/// @notice Function to get the vote details by post ID
/// @param _postId Unique identifier of the post
/// @return The post's voting information
function getVoteByPostId(uint256 _postId)
external
view
returns (Vote memory)
{
return voteMap[_postId];
}
//*************************************PostViolation**************************************************//
/// @notice Function to get the violation report of a post
/// @param _postId Unique identifier of the post
/// @return The post violation report
function getPostViolation(uint256 _postId)
external
view
returns (Violation memory)
{
return postViolation[postById[_postId].creator];
}
/// @notice Function to report the post violation
/// @dev Require a valid post ID and the number of down votes should be equal or exceeds the threshold
/// @param _postId Unique identifier of the post
/// @return suspensionDays The number of days user is suspended for the violation
/// @return ban If true, user is permanently banned from the application
function reportPostViolation(uint256 _postId)
external
returns (uint256 suspensionDays, bool ban)
{
Post memory post = postById[_postId];
require(post.id == _postId, "Check the post ID");
Vote memory postVote = voteMap[_postId];
require(
postVote.downVote >= downVoteThreshold,
"Can not take down the post"
);
Violation storage violation = postViolation[post.creator];
violation.postIds.push(_postId);
violation.count += 1;
violation.postCreator = post.creator;
post.visible = false;
postOperations(post);
if (violation.count <= numberOfExcuses) {
userDetails[post.creator].status = UserStatus.Suspend;
emit PostViolation(
violation.postIds,
violation.count,
suspensionPeriod,
false,
violation.postCreator
);
return (suspensionPeriod, false);
} else {
delete userByAddress[post.creator];
userDetails[post.creator].status = UserStatus.banned;
emit PostViolation(
violation.postIds,
violation.count,
0,
true,
violation.postCreator
);
return (0, true);
}
}
//*************************************MintingNFTPost**************************************************//
/// @notice Allow user to minf NFT of their post if they get enough upvotes
/// @param tokenURI Post metadata (stored on ipfs)
/// @param _id The unique identifier of the post
/// @param _amount amount to set as price of NFT
/// @return The Item id
function mintNFT(
string memory tokenURI,
uint256 _id,
uint256 _amount
) public returns (uint256) {
Vote storage voteInstance = voteMap[_id];
require(_amount > 0);
require(msg.sender == postById[_id].creator);
require(voteInstance.upVote == upVoteThreshold, "Not enough votes");
_idCounter.increment();
uint256 newItemId = _idCounter.current();
_mint(postById[_id].creator, newItemId);
_setTokenURI(newItemId, tokenURI);
setNftPrice(_id, _amount);
return newItemId;
}
/// @notice ERC721Upgradeable and ERC721Upgradeable include supportsInterface so we need to override them.
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, AccessControlUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function getNftPrice(uint256 _tokenId) public view returns (uint256) {
require(_exists(_tokenId));
return currentPrice[_tokenId];
}
/// @notice set the price of the NFT post
/// @param _tokenId The unique identifier of the NFT post
/// @param _amount amount to set as price of NFT
function setNftPrice(uint256 _tokenId, uint256 _amount) internal {
require(_exists(_tokenId));
require(_amount > 0);
currentPrice[_tokenId] = _amount;
}
/// @notice Allow users to buy the NFT
/// @param _tokenId The unique identifier of the NFT post
/// @param _amount amount to pay for the NFT
function buyNFT(uint256 _tokenId, uint256 _amount) public {
require(_exists(_tokenId));
require(_amount >= currentPrice[_tokenId]);
token.transfer(postById[_tokenId].creator, _amount);
safeTransferFrom(postById[_tokenId].creator, msg.sender, _tokenId);
}
}
| @notice Fetch all the posts created accross users @return The list of post records | function getAllPosts() external onlyRegisteredUser(msg.sender) view returns (Post[] memory) {
return posts;
}
| 2,513,552 | [
1,
5005,
777,
326,
10775,
2522,
4078,
3984,
3677,
327,
1021,
666,
434,
1603,
3853,
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,
5514,
24983,
1435,
3903,
1338,
10868,
1299,
12,
3576,
18,
15330,
13,
1476,
1135,
261,
3349,
8526,
3778,
13,
288,
203,
3639,
327,
10775,
31,
203,
565,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
contract LotteryFactory {
// contract profit
uint public commissionSum;
// default lottery params
Params public defaultParams;
// lotteries
Lottery[] public lotteries;
// lotteries count
uint public lotteryCount;
// contract owner address
address public owner;
struct Lottery {
mapping(address => uint) ownerTokenCount;
mapping(address => uint) ownerTokenCountToSell;
mapping(address => uint) sellerId;
address[] sellingAddresses;
uint[] sellingAmounts;
uint createdAt;
uint tokenCount;
uint tokenCountToSell;
uint winnerSum;
bool prizeRedeemed;
address winner;
address[] participants;
Params params;
}
// lottery params
struct Params {
uint gameDuration;
uint initialTokenPrice;
uint durationToTokenPriceUp;
uint tokenPriceIncreasePercent;
uint tradeCommission;
uint winnerCommission;
}
// event fired on purchase error, when user tries to buy a token from a seller
event PurchaseError(address oldOwner, uint amount);
/**
* Throws if called by account different from the owner account
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Sets owner and default lottery params
*/
constructor() public {
// set owner
owner = msg.sender;
// set default params
updateParams(4 hours, 0.01 ether, 15 minutes, 10, 1, 10);
// create a new lottery
_createNewLottery();
}
/**
* @dev Approves tokens for selling
* @param _tokenCount amount of tokens to place for selling
*/
function approveToSell(uint _tokenCount) public {
Lottery storage lottery = lotteries[lotteryCount - 1];
// check that user has enough tokens to sell
require(lottery.ownerTokenCount[msg.sender] - lottery.ownerTokenCountToSell[msg.sender] >= _tokenCount);
// if there are no sales or this is user's first sale
if(lottery.sellingAddresses.length == 0 || lottery.sellerId[msg.sender] == 0 && lottery.sellingAddresses[0] != msg.sender) {
uint sellingAddressesCount = lottery.sellingAddresses.push(msg.sender);
uint sellingAmountsCount = lottery.sellingAmounts.push(_tokenCount);
assert(sellingAddressesCount == sellingAmountsCount);
lottery.sellerId[msg.sender] = sellingAddressesCount - 1;
} else {
// seller exists and placed at least 1 sale
uint sellerIndex = lottery.sellerId[msg.sender];
lottery.sellingAmounts[sellerIndex] += _tokenCount;
}
// update global lottery variables
lottery.ownerTokenCountToSell[msg.sender] += _tokenCount;
lottery.tokenCountToSell += _tokenCount;
}
/**
* @dev Returns token balance by user address
* @param _user user address
* @return token acount on the user balance
*/
function balanceOf(address _user) public view returns(uint) {
Lottery storage lottery = lotteries[lotteryCount - 1];
return lottery.ownerTokenCount[_user];
}
/**
* @dev Returns selling token balance by user address
* @param _user user address
* @return token acount selling by user
*/
function balanceSellingOf(address _user) public view returns(uint) {
Lottery storage lottery = lotteries[lotteryCount - 1];
return lottery.ownerTokenCountToSell[_user];
}
/**
* @dev Buys tokens
*/
function buyTokens() public payable {
if(_isNeededNewLottery()) _createNewLottery();
// get latest lottery
Lottery storage lottery = lotteries[lotteryCount - 1];
// get token count to buy
uint price = _getCurrentTokenPrice();
uint tokenCountToBuy = msg.value / price;
// any extra eth added to winner sum
uint rest = msg.value - tokenCountToBuy * price;
if( rest > 0 ){
lottery.winnerSum = lottery.winnerSum + rest;
}
// check that user wants to buy at least 1 token
require(tokenCountToBuy > 0);
// buy tokens from sellers
uint tokenCountToBuyFromSeller = _getTokenCountToBuyFromSeller(tokenCountToBuy);
if(tokenCountToBuyFromSeller > 0) {
_buyTokensFromSeller(tokenCountToBuyFromSeller);
}
// buy tokens from system
uint tokenCountToBuyFromSystem = tokenCountToBuy - tokenCountToBuyFromSeller;
if(tokenCountToBuyFromSystem > 0) {
_buyTokensFromSystem(tokenCountToBuyFromSystem);
}
// add sender to participants
_addToParticipants(msg.sender);
// update winner values
lottery.winnerSum += tokenCountToBuyFromSystem * price;
lottery.winner = _getWinner();
}
/**
* @dev Removes tokens from selling
* @param _tokenCount amount of tokens to remove from selling
*/
function disapproveToSell(uint _tokenCount) public {
Lottery storage lottery = lotteries[lotteryCount - 1];
// check that user has enough tokens to cancel selling
require(lottery.ownerTokenCountToSell[msg.sender] >= _tokenCount);
// remove tokens from selling
uint sellerIndex = lottery.sellerId[msg.sender];
lottery.sellingAmounts[sellerIndex] -= _tokenCount;
// update global lottery variables
lottery.ownerTokenCountToSell[msg.sender] -= _tokenCount;
lottery.tokenCountToSell -= _tokenCount;
}
/**
* @dev Returns lottery details by index
* @param _index lottery index
* @return lottery details
*/
function getLotteryAtIndex(uint _index) public view returns(
uint createdAt,
uint tokenCount,
uint tokenCountToSell,
uint winnerSum,
address winner,
bool prizeRedeemed,
address[] participants,
uint paramGameDuration,
uint paramInitialTokenPrice,
uint paramDurationToTokenPriceUp,
uint paramTokenPriceIncreasePercent,
uint paramTradeCommission,
uint paramWinnerCommission
) {
// check that lottery exists
require(_index < lotteryCount);
// return lottery details
Lottery memory lottery = lotteries[_index];
createdAt = lottery.createdAt;
tokenCount = lottery.tokenCount;
tokenCountToSell = lottery.tokenCountToSell;
winnerSum = lottery.winnerSum;
winner = lottery.winner;
prizeRedeemed = lottery.prizeRedeemed;
participants = lottery.participants;
paramGameDuration = lottery.params.gameDuration;
paramInitialTokenPrice = lottery.params.initialTokenPrice;
paramDurationToTokenPriceUp = lottery.params.durationToTokenPriceUp;
paramTokenPriceIncreasePercent = lottery.params.tokenPriceIncreasePercent;
paramTradeCommission = lottery.params.tradeCommission;
paramWinnerCommission = lottery.params.winnerCommission;
}
/**
* @dev Returns arrays of addresses who sell tokens and corresponding amounts
* @return array of addresses who sell tokens and array of amounts
*/
function getSales() public view returns(address[], uint[]) {
// get latest lottery
Lottery memory lottery = lotteries[lotteryCount - 1];
// return array of addresses who sell tokens and amounts
return (lottery.sellingAddresses, lottery.sellingAmounts);
}
/**
* @dev Returns top users by balances for current lottery
* @param _n number of top users to find
* @return array of addresses and array of balances sorted in balance descend
*/
function getTop(uint _n) public view returns(address[], uint[]) {
// check that n > 0
require(_n > 0);
// get latest lottery
Lottery memory lottery = lotteries[lotteryCount - 1];
// find top n users with highest token balances
address[] memory resultAddresses = new address[](_n);
uint[] memory resultBalances = new uint[](_n);
for(uint i = 0; i < _n; i++) {
// if current iteration is more than number of participants then continue
if(i > lottery.participants.length - 1) continue;
// if 1st iteration then set 0 values
uint prevMaxBalance = i == 0 ? 0 : resultBalances[i-1];
address prevAddressWithMax = i == 0 ? address(0) : resultAddresses[i-1];
uint currentMaxBalance = 0;
address currentAddressWithMax = address(0);
for(uint j = 0; j < lottery.participants.length; j++) {
uint balance = balanceOf(lottery.participants[j]);
// if first iteration then simply find max
if(i == 0) {
if(balance > currentMaxBalance) {
currentMaxBalance = balance;
currentAddressWithMax = lottery.participants[j];
}
} else {
// find balance that is less or equal to the prev max
if(prevMaxBalance >= balance && balance > currentMaxBalance && lottery.participants[j] != prevAddressWithMax) {
currentMaxBalance = balance;
currentAddressWithMax = lottery.participants[j];
}
}
}
resultAddresses[i] = currentAddressWithMax;
resultBalances[i] = currentMaxBalance;
}
return(resultAddresses, resultBalances);
}
/**
* @dev Returns seller id by user address
* @param _user user address
* @return seller id/index
*/
function sellerIdOf(address _user) public view returns(uint) {
Lottery storage lottery = lotteries[lotteryCount - 1];
return lottery.sellerId[_user];
}
/**
* @dev Updates lottery parameters
* @param _gameDuration duration of the lottery in seconds
* @param _initialTokenPrice initial price for 1 token in wei
* @param _durationToTokenPriceUp how many seconds should pass to increase token price
* @param _tokenPriceIncreasePercent percentage of token increase. ex: 2 will increase token price by 2% each time interval
* @param _tradeCommission commission in percentage for trading tokens. When user1 sells token to user2 for 1.15 eth then commision applied
* @param _winnerCommission commission in percentage for winning sum
*/
function updateParams(
uint _gameDuration,
uint _initialTokenPrice,
uint _durationToTokenPriceUp,
uint _tokenPriceIncreasePercent,
uint _tradeCommission,
uint _winnerCommission
) public onlyOwner {
Params memory params;
params.gameDuration = _gameDuration;
params.initialTokenPrice = _initialTokenPrice;
params.durationToTokenPriceUp = _durationToTokenPriceUp;
params.tokenPriceIncreasePercent = _tokenPriceIncreasePercent;
params.tradeCommission = _tradeCommission;
params.winnerCommission = _winnerCommission;
defaultParams = params;
}
/**
* @dev Withdraws commission sum to the owner
*/
function withdraw() public onlyOwner {
// check that commision > 0
require(commissionSum > 0);
// save commission for later transfer and reset
uint commissionSumToTransfer = commissionSum;
commissionSum = 0;
// transfer commission to owner
owner.transfer(commissionSumToTransfer);
}
/**
* @dev Withdraws ether for winner
* @param _lotteryIndex lottery index
*/
function withdrawForWinner(uint _lotteryIndex) public {
// check that lottery exists
require(lotteries.length > _lotteryIndex);
// check that sender is winner
Lottery storage lottery = lotteries[_lotteryIndex];
require(lottery.winner == msg.sender);
// check that lottery is over
require(now > lottery.createdAt + lottery.params.gameDuration);
// check that prize is not redeemed
require(!lottery.prizeRedeemed);
// update contract commission sum and winner sum
uint winnerCommissionSum = _getValuePartByPercent(lottery.winnerSum, lottery.params.winnerCommission);
commissionSum += winnerCommissionSum;
uint winnerSum = lottery.winnerSum - winnerCommissionSum;
// mark lottery as redeemed
lottery.prizeRedeemed = true;
// send winner his prize
lottery.winner.transfer(winnerSum);
}
/**
* @dev Disallow users to send ether directly to the contract
*/
function() public payable {
revert();
}
/**
* @dev Adds user address to participants
* @param _user user address
*/
function _addToParticipants(address _user) internal {
// check that user is not in participants
Lottery storage lottery = lotteries[lotteryCount - 1];
bool isParticipant = false;
for(uint i = 0; i < lottery.participants.length; i++) {
if(lottery.participants[i] == _user) {
isParticipant = true;
break;
}
}
if(!isParticipant) {
lottery.participants.push(_user);
}
}
/**
* @dev Buys tokens from sellers
* @param _tokenCountToBuy amount of tokens to buy from sellers
*/
function _buyTokensFromSeller(uint _tokenCountToBuy) internal {
// check that token count is not 0
require(_tokenCountToBuy > 0);
// get latest lottery
Lottery storage lottery = lotteries[lotteryCount - 1];
// get current token price and commission sum
uint currentTokenPrice = _getCurrentTokenPrice();
uint currentCommissionSum = _getValuePartByPercent(currentTokenPrice, lottery.params.tradeCommission);
uint purchasePrice = currentTokenPrice - currentCommissionSum;
// foreach selling amount
uint tokensLeftToBuy = _tokenCountToBuy;
for(uint i = 0; i < lottery.sellingAmounts.length; i++) {
// if amount != 0 and buyer does not purchase his own tokens
if(lottery.sellingAmounts[i] != 0 && lottery.sellingAddresses[i] != msg.sender) {
address oldOwner = lottery.sellingAddresses[i];
// find how many tokens to substitute
uint tokensToSubstitute;
if(tokensLeftToBuy < lottery.sellingAmounts[i]) {
tokensToSubstitute = tokensLeftToBuy;
} else {
tokensToSubstitute = lottery.sellingAmounts[i];
}
// update old owner balance and send him ether
lottery.sellingAmounts[i] -= tokensToSubstitute;
lottery.ownerTokenCount[oldOwner] -= tokensToSubstitute;
lottery.ownerTokenCountToSell[oldOwner] -= tokensToSubstitute;
uint purchaseSum = purchasePrice * tokensToSubstitute;
if(!oldOwner.send(purchaseSum)) {
emit PurchaseError(oldOwner, purchaseSum);
}
// check if user bought enough
tokensLeftToBuy -= tokensToSubstitute;
if(tokensLeftToBuy == 0) break;
}
}
// update contract variables
commissionSum += _tokenCountToBuy * purchasePrice;
lottery.ownerTokenCount[msg.sender] += _tokenCountToBuy;
lottery.tokenCountToSell -= _tokenCountToBuy;
}
/**
* @dev Buys tokens from system(mint) for sender
* @param _tokenCountToBuy token count to buy
*/
function _buyTokensFromSystem(uint _tokenCountToBuy) internal {
// check that token count is not 0
require(_tokenCountToBuy > 0);
// get latest lottery
Lottery storage lottery = lotteries[lotteryCount - 1];
// mint tokens for buyer
lottery.ownerTokenCount[msg.sender] += _tokenCountToBuy;
// update lottery values
lottery.tokenCount += _tokenCountToBuy;
}
/**
* @dev Creates a new lottery
*/
function _createNewLottery() internal {
Lottery memory lottery;
lottery.createdAt = _getNewLotteryCreatedAt();
lottery.params = defaultParams;
lotteryCount = lotteries.push(lottery);
}
/**
* @dev Returns current price for 1 token
* @return token price
*/
function _getCurrentTokenPrice() internal view returns(uint) {
Lottery memory lottery = lotteries[lotteryCount - 1];
uint diffInSec = now - lottery.createdAt;
uint stageCount = diffInSec / lottery.params.durationToTokenPriceUp;
uint price = lottery.params.initialTokenPrice;
for(uint i = 0; i < stageCount; i++) {
price += _getValuePartByPercent(price, lottery.params.tokenPriceIncreasePercent);
}
return price;
}
/**
* @dev Returns new lottery created at.
* Ex: latest lottery started at 0:00 and finished at 6:00. Now it is 7:00. User buys token. New lottery createdAt will be 06:00:01.
* @return new lottery created at timestamp
*/
function _getNewLotteryCreatedAt() internal view returns(uint) {
// if there are no lotteries then return now
if(lotteries.length == 0) return now;
// else loop while new created at time is not found
// get latest lottery end time
uint latestEndAt = lotteries[lotteryCount - 1].createdAt + lotteries[lotteryCount - 1].params.gameDuration;
// get next lottery end time
uint nextEndAt = latestEndAt + defaultParams.gameDuration;
while(now > nextEndAt) {
nextEndAt += defaultParams.gameDuration;
}
return nextEndAt - defaultParams.gameDuration;
}
/**
* @dev Returns number of tokens that can be bought from seller
* @param _tokenCountToBuy token count to buy
* @return number of tokens that can be bought from seller
*/
function _getTokenCountToBuyFromSeller(uint _tokenCountToBuy) internal view returns(uint) {
// check that token count is not 0
require(_tokenCountToBuy > 0);
// get latest lottery
Lottery storage lottery = lotteries[lotteryCount - 1];
// check that total token count on sale is more that user has
require(lottery.tokenCountToSell >= lottery.ownerTokenCountToSell[msg.sender]);
// substitute user's token on sale count from total count
uint tokenCountToSell = lottery.tokenCountToSell - lottery.ownerTokenCountToSell[msg.sender];
// if there are no tokens to sell then return 0
if(tokenCountToSell == 0) return 0;
// if there are less tokens to sell than we need
if(tokenCountToSell < _tokenCountToBuy) {
return tokenCountToSell;
} else {
// contract has all tokens to buy from sellers
return _tokenCountToBuy;
}
}
/**
* @dev Returns part of number by percent. Ex: (200, 1) => 2
* @param _initialValue initial number
* @param _percent percentage
* @return part of number by percent
*/
function _getValuePartByPercent(uint _initialValue, uint _percent) internal pure returns(uint) {
uint onePercentValue = _initialValue / 100;
return onePercentValue * _percent;
}
/**
* @dev Returns winner address
* @return winner address
*/
function _getWinner() internal view returns(address) {
Lottery storage lottery = lotteries[lotteryCount - 1];
// if there are no participants then return 0x00 address
if(lottery.participants.length == 0) return address(0);
// set the 1st participant as winner
address winner = lottery.participants[0];
uint maxTokenCount = 0;
// loop through all participants to find winner
for(uint i = 0; i < lottery.participants.length; i++) {
uint currentTokenCount = lottery.ownerTokenCount[lottery.participants[i]];
if(currentTokenCount > maxTokenCount) {
winner = lottery.participants[i];
maxTokenCount = currentTokenCount;
}
}
return winner;
}
/**
* @dev Checks whether new lottery should be created
* @return true if new lottery needs to be created false otherwise
*/
function _isNeededNewLottery() internal view returns(bool) {
// if there are no lotteries then return true
if(lotteries.length == 0) return true;
// if now is more than lottery end time then return true else false
Lottery memory lottery = lotteries[lotteries.length - 1];
return now > lottery.createdAt + defaultParams.gameDuration;
}
} | * @dev Returns selling token balance by user address @param _user user address @return token acount selling by user/ | function balanceSellingOf(address _user) public view returns(uint) {
Lottery storage lottery = lotteries[lotteryCount - 1];
return lottery.ownerTokenCountToSell[_user];
}
| 1,733,488 | [
1,
1356,
357,
2456,
1147,
11013,
635,
729,
1758,
225,
389,
1355,
729,
1758,
327,
1147,
1721,
592,
357,
2456,
635,
729,
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
] | [
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,
202,
915,
11013,
55,
1165,
310,
951,
12,
2867,
389,
1355,
13,
1071,
1476,
1135,
12,
11890,
13,
288,
203,
202,
202,
48,
352,
387,
93,
2502,
17417,
387,
93,
273,
17417,
387,
606,
63,
23372,
387,
93,
1380,
300,
404,
15533,
203,
202,
202,
2463,
17417,
387,
93,
18,
8443,
1345,
1380,
774,
55,
1165,
63,
67,
1355,
15533,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
import {DepositLiquidation} from "./DepositLiquidation.sol";
import {DepositUtils} from "./DepositUtils.sol";
import {DepositFunding} from "./DepositFunding.sol";
import {DepositRedemption} from "./DepositRedemption.sol";
import {DepositStates} from "./DepositStates.sol";
import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol";
import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {FeeRebateToken} from "../system/FeeRebateToken.sol";
import "../system/DepositFactoryAuthority.sol";
// solium-disable function-order
// Below, a few functions must be public to allow bytes memory parameters, but
// their being so triggers errors because public functions should be grouped
// below external functions. Since these would be external if it were possible,
// we ignore the issue.
/// @title tBTC Deposit
/// @notice This is the main contract for tBTC. It is the state machine that
/// (through various libraries) handles bitcoin funding, bitcoin-spv
/// proofs, redemption, liquidation, and fraud logic.
/// @dev This contract presents a public API that exposes the following
/// libraries:
///
/// - `DepositFunding`
/// - `DepositLiquidaton`
/// - `DepositRedemption`,
/// - `DepositStates`
/// - `DepositUtils`
/// - `OutsourceDepositLogging`
/// - `TBTCConstants`
///
/// Where these libraries require deposit state, this contract's state
/// variable `self` is used. `self` is a struct of type
/// `DepositUtils.Deposit` that contains all aspects of the deposit state
/// itself.
contract Deposit is DepositFactoryAuthority {
using DepositRedemption for DepositUtils.Deposit;
using DepositFunding for DepositUtils.Deposit;
using DepositLiquidation for DepositUtils.Deposit;
using DepositUtils for DepositUtils.Deposit;
using DepositStates for DepositUtils.Deposit;
DepositUtils.Deposit self;
/// @dev Deposit should only be _constructed_ once. New deposits are created
/// using the `DepositFactory.createDeposit` method, and are clones of
/// the constructed deposit. The factory will set the initial values
/// for a new clone using `initializeDeposit`.
constructor () public {
// The constructed Deposit will never be used, so the deposit factory
// address can be anything. Clones are updated as per above.
initialize(address(0xdeadbeef));
}
/// @notice Deposits do not accept arbitrary ETH.
function () external payable {
require(msg.data.length == 0, "Deposit contract was called with unknown function selector.");
}
//----------------------------- METADATA LOOKUP ------------------------------//
/// @notice Get this deposit's BTC lot size in satoshis.
/// @return uint64 lot size in satoshis.
function lotSizeSatoshis() external view returns (uint64){
return self.lotSizeSatoshis;
}
/// @notice Get this deposit's lot size in TBTC.
/// @dev This is the same as lotSizeSatoshis(), but is multiplied to scale
/// to 18 decimal places.
/// @return uint256 lot size in TBTC precision (max 18 decimal places).
function lotSizeTbtc() external view returns (uint256){
return self.lotSizeTbtc();
}
/// @notice Get the signer fee for this deposit, in TBTC.
/// @dev This is the one-time fee required by the signers to perform the
/// tasks needed to maintain a decentralized and trustless model for
/// tBTC. It is a percentage of the deposit's lot size.
/// @return Fee amount in TBTC.
function signerFeeTbtc() external view returns (uint256) {
return self.signerFeeTbtc();
}
/// @notice Get the integer representing the current state.
/// @dev We implement this because contracts don't handle foreign enums
/// well. See `DepositStates` for more info on states.
/// @return The 0-indexed state from the DepositStates enum.
function currentState() external view returns (uint256) {
return uint256(self.currentState);
}
/// @notice Check if the Deposit is in ACTIVE state.
/// @return True if state is ACTIVE, false otherwise.
function inActive() external view returns (bool) {
return self.inActive();
}
/// @notice Get the contract address of the BondedECDSAKeep associated with
/// this Deposit.
/// @dev The keep contract address is saved on Deposit initialization.
/// @return Address of the Keep contract.
function keepAddress() external view returns (address) {
return self.keepAddress;
}
/// @notice Retrieve the remaining term of the deposit in seconds.
/// @dev The value accuracy is not guaranteed since block.timestmap can be
/// lightly manipulated by miners.
/// @return The remaining term of the deposit in seconds. 0 if already at
/// term.
function remainingTerm() external view returns(uint256){
return self.remainingTerm();
}
/// @notice Get the current collateralization level for this Deposit.
/// @dev This value represents the percentage of the backing BTC value the
/// signers currently must hold as bond.
/// @return The current collateralization level for this deposit.
function collateralizationPercentage() external view returns (uint256) {
return self.collateralizationPercentage();
}
/// @notice Get the initial collateralization level for this Deposit.
/// @dev This value represents the percentage of the backing BTC value
/// the signers hold initially. It is set at creation time.
/// @return The initial collateralization level for this deposit.
function initialCollateralizedPercent() external view returns (uint16) {
return self.initialCollateralizedPercent;
}
/// @notice Get the undercollateralization level for this Deposit.
/// @dev This collateralization level is semi-critical. If the
/// collateralization level falls below this percentage the Deposit can
/// be courtesy-called by calling `notifyCourtesyCall`. This value
/// represents the percentage of the backing BTC value the signers must
/// hold as bond in order to not be undercollateralized. It is set at
/// creation time. Note that the value for new deposits in TBTCSystem
/// can be changed by governance, but the value for a particular
/// deposit is static once the deposit is created.
/// @return The undercollateralized level for this deposit.
function undercollateralizedThresholdPercent() external view returns (uint16) {
return self.undercollateralizedThresholdPercent;
}
/// @notice Get the severe undercollateralization level for this Deposit.
/// @dev This collateralization level is critical. If the collateralization
/// level falls below this percentage the Deposit can get liquidated.
/// This value represents the percentage of the backing BTC value the
/// signers must hold as bond in order to not be severely
/// undercollateralized. It is set at creation time. Note that the
/// value for new deposits in TBTCSystem can be changed by governance,
/// but the value for a particular deposit is static once the deposit
/// is created.
/// @return The severely undercollateralized level for this deposit.
function severelyUndercollateralizedThresholdPercent() external view returns (uint16) {
return self.severelyUndercollateralizedThresholdPercent;
}
/// @notice Get the value of the funding UTXO.
/// @dev This call will revert if the deposit is not in a state where the
/// UTXO info should be valid. In particular, before funding proof is
/// successfully submitted (i.e. in states START,
/// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), this value
/// would not be valid.
/// @return The value of the funding UTXO in satoshis.
function utxoValue() external view returns (uint256){
require(
! self.inFunding(),
"Deposit has not yet been funded and has no available funding info"
);
return self.utxoValue();
}
/// @notice Returns information associated with the funding UXTO.
/// @dev This call will revert if the deposit is not in a state where the
/// funding info should be valid. In particular, before funding proof
/// is successfully submitted (i.e. in states START,
/// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of
/// these values are set or valid.
/// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint).
function fundingInfo() external view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) {
require(
! self.inFunding(),
"Deposit has not yet been funded and has no available funding info"
);
return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint);
}
/// @notice Calculates the amount of value at auction right now.
/// @dev This call will revert if the deposit is not in a state where an
/// auction is currently in progress.
/// @return The value in wei that would be received in exchange for the
/// deposit's lot size in TBTC if `purchaseSignerBondsAtAuction`
/// were called at the time this function is called.
function auctionValue() external view returns (uint256) {
require(
self.inSignerLiquidation(),
"Deposit has no funds currently at auction"
);
return self.auctionValue();
}
/// @notice Get caller's ETH withdraw allowance.
/// @dev Generally ETH is only available to withdraw after the deposit
/// reaches a closed state. The amount reported is for the sender, and
/// can be withdrawn using `withdrawFunds` if the deposit is in an end
/// state.
/// @return The withdraw allowance in wei.
function withdrawableAmount() external view returns (uint256) {
return self.getWithdrawableAmount();
}
//------------------------------ FUNDING FLOW --------------------------------//
/// @notice Notify the contract that signing group setup has timed out if
/// retrieveSignerPubkey is not successfully called within the
/// allotted time.
/// @dev This is considered a signer fault, and the signers' bonds are used
/// to make the deposit setup fee available for withdrawal by the TDT
/// holder as a refund. The remainder of the signers' bonds are
/// returned to the bonding pool and the signers are released from any
/// further responsibilities. Reverts if the deposit is not awaiting
/// signer setup or if the signing group formation timeout has not
/// elapsed.
function notifySignerSetupFailed() external {
self.notifySignerSetupFailed();
}
/// @notice Notify the contract that the ECDSA keep has generated a public
/// key so the deposit contract can pull it in.
/// @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a
/// RegisteredPubkey event with the two components. Reverts if the
/// deposit is not awaiting signer setup, if the generated public key
/// is unset or has incorrect length, or if the public key has a 0
/// X or Y value.
function retrieveSignerPubkey() external {
self.retrieveSignerPubkey();
}
/// @notice Notify the contract that the funding phase of the deposit has
/// timed out if `provideBTCFundingProof` is not successfully called
/// within the allotted time. Any sent BTC is left under control of
/// the signer group, and the funder can use `requestFunderAbort` to
/// request an at-signer-discretion return of any BTC sent to a
/// deposit that has been notified of a funding timeout.
/// @dev This is considered a funder fault, and the funder's payment for
/// opening the deposit is not refunded. Emits a SetupFailed event.
/// Reverts if the funding timeout has not yet elapsed, or if the
/// deposit is not currently awaiting funding proof.
function notifyFundingTimedOut() external {
self.notifyFundingTimedOut();
}
/// @notice Requests a funder abort for a failed-funding deposit; that is,
/// requests the return of a sent UTXO to _abortOutputScript. It
/// imposes no requirements on the signing group. Signers should
/// send their UTXO to the requested output script, but do so at
/// their discretion and with no penalty for failing to do so. This
/// can be used for example when a UTXO is sent that is the wrong
/// size for the lot.
/// @dev This is a self-admitted funder fault, and is only be callable by
/// the TDT holder. This function emits the FunderAbortRequested event,
/// but stores no additional state.
/// @param _abortOutputScript The output script the funder wishes to request
/// a return of their UTXO to.
function requestFunderAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters
require(
self.depositOwner() == msg.sender,
"Only TDT holder can request funder abort"
);
self.requestFunderAbort(_abortOutputScript);
}
/// @notice Anyone can provide a signature corresponding to the signers'
/// public key to prove fraud during funding. Note that during
/// funding no signature has been requested from the signers, so
/// any signature is effectively fraud.
/// @dev Calls out to the keep to verify if there was fraud.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature (v,r,s) tuple.
/// @param _preimage The sha256 preimage of the digest.
function provideFundingECDSAFraudProof(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public { // not external to allow bytes memory parameters
self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage);
}
/// @notice Anyone may submit a funding proof to the deposit showing that
/// a transaction was submitted and sufficiently confirmed on the
/// Bitcoin chain transferring the deposit lot size's amount of BTC
/// to the signer-controlled private key corresopnding to this
/// deposit. This will move the deposit into an active state.
/// @dev Takes a pre-parsed transaction and calculates values needed to
/// verify funding.
/// @param _txVersion Transaction version number (4-byte little-endian).
/// @param _txInputVector All transaction inputs prepended by the number of
/// inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number
/// of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _fundingOutputIndex Index of funding output in _txOutputVector
/// (0-indexed).
/// @param _merkleProof The merkle proof of transaction inclusion in a
/// block.
/// @param _txIndexInBlock Transaction index in the block (0-indexed).
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers,
/// lowest height first.
function provideBTCFundingProof(
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public { // not external to allow bytes memory parameters
self.provideBTCFundingProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_fundingOutputIndex,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
}
//---------------------------- LIQUIDATION FLOW ------------------------------//
/// @notice Notify the contract that the signers are undercollateralized.
/// @dev This call will revert if the signers are not in fact
/// undercollateralized according to the price feed. After
/// TBTCConstants.COURTESY_CALL_DURATION, courtesy call times out and
/// regular abort liquidation occurs; see
/// `notifyCourtesyTimedOut`.
function notifyCourtesyCall() external {
self.notifyCourtesyCall();
}
/// @notice Notify the contract that the signers' bond value has recovered
/// enough to be considered sufficiently collateralized.
/// @dev This call will revert if collateral is still below the
/// undercollateralized threshold according to the price feed.
function exitCourtesyCall() external {
self.exitCourtesyCall();
}
/// @notice Notify the contract that the courtesy period has expired and the
/// deposit should move into liquidation.
/// @dev This call will revert if the courtesy call period has not in fact
/// expired or is not in the courtesy call state. Courtesy call
/// expiration is treated as an abort, and is handled by seizing signer
/// bonds and putting them up for auction for the lot size amount in
/// TBTC (see `purchaseSignerBondsAtAuction`). Emits a
/// LiquidationStarted event. The caller is captured as the liquidation
/// initiator, and is eligible for 50% of any bond left after the
/// auction is completed.
function notifyCourtesyCallExpired() external {
self.notifyCourtesyCallExpired();
}
/// @notice Notify the contract that the signers are undercollateralized.
/// @dev Calls out to the system for oracle info.
/// @dev This call will revert if the signers are not in fact severely
/// undercollateralized according to the price feed. Severe
/// undercollateralization is treated as an abort, and is handled by
/// seizing signer bonds and putting them up for auction in exchange
/// for the lot size amount in TBTC (see
/// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event.
/// The caller is captured as the liquidation initiator, and is
/// eligible for 50% of any bond left after the auction is completed.
function notifyUndercollateralizedLiquidation() external {
self.notifyUndercollateralizedLiquidation();
}
/// @notice Anyone can provide a signature corresponding to the signers'
/// public key that was not requested to prove fraud. A redemption
/// request and a redemption fee increase are the only ways to
/// request a signature from the signers.
/// @dev This call will revert if the underlying keep cannot verify that
/// there was fraud. Fraud is handled by seizing signer bonds and
/// putting them up for auction in exchange for the lot size amount in
/// TBTC (see `purchaseSignerBondsAtAuction`). Emits a
/// LiquidationStarted event. The caller is captured as the liquidation
/// initiator, and is eligible for any bond left after the auction is
/// completed.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature (v,r,s) tuple.
/// @param _preimage The sha256 preimage of the digest.
function provideECDSAFraudProof(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public { // not external to allow bytes memory parameters
self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage);
}
/// @notice Notify the contract that the signers have failed to produce a
/// signature for a redemption request in the allotted time.
/// @dev This is considered an abort, and is punished by seizing signer
/// bonds and putting them up for auction. Emits a LiquidationStarted
/// event and a Liquidated event and sends the full signer bond to the
/// redeemer. Reverts if the deposit is not currently awaiting a
/// signature or if the allotted time has not yet elapsed. The caller
/// is captured as the liquidation initiator, and is eligible for 50%
/// of any bond left after the auction is completed.
function notifyRedemptionSignatureTimedOut() external {
self.notifyRedemptionSignatureTimedOut();
}
/// @notice Notify the contract that the deposit has failed to receive a
/// redemption proof in the allotted time.
/// @dev This call will revert if the deposit is not currently awaiting a
/// signature or if the allotted time has not yet elapsed. This is
/// considered an abort, and is punished by seizing signer bonds and
/// putting them up for auction for the lot size amount in TBTC (see
/// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event.
/// The caller is captured as the liquidation initiator, and
/// is eligible for 50% of any bond left after the auction is
/// completed.
function notifyRedemptionProofTimedOut() external {
self.notifyRedemptionProofTimedOut();
}
/// @notice Closes an auction and purchases the signer bonds by transferring
/// the lot size in TBTC to the redeemer, if there is one, or to the
/// TDT holder if not. Any bond amount that is not currently up for
/// auction is either made available for the liquidation initiator
/// to withdraw (for fraud) or split 50-50 between the initiator and
/// the signers (for abort or collateralization issues).
/// @dev The amount of ETH given for the transferred TBTC can be read using
/// the `auctionValue` function; note, however, that the function's
/// value is only static during the specific block it is queried, as it
/// varies by block timestamp.
function purchaseSignerBondsAtAuction() external {
self.purchaseSignerBondsAtAuction();
}
//---------------------------- REDEMPTION FLOW -------------------------------//
/// @notice Get TBTC amount required for redemption by a specified
/// _redeemer.
/// @dev This call will revert if redemption is not possible by _redeemer.
/// @param _redeemer The deposit redeemer whose TBTC requirement is being
/// requested.
/// @return The amount in TBTC needed by the `_redeemer` to redeem the
/// deposit.
function getRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){
(uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, false);
return tbtcPayment;
}
/// @notice Get TBTC amount required for redemption assuming _redeemer
/// is this deposit's owner (TDT holder).
/// @param _redeemer The assumed owner of the deposit's TDT .
/// @return The amount in TBTC needed to redeem the deposit.
function getOwnerRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){
(uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, true);
return tbtcPayment;
}
/// @notice Requests redemption of this deposit, meaning the transmission,
/// by the signers, of the deposit's UTXO to the specified Bitocin
/// output script. Requires approving the deposit to spend the
/// amount of TBTC needed to redeem.
/// @dev The amount of TBTC needed to redeem can be looked up using the
/// `getRedemptionTbtcRequirement` or `getOwnerRedemptionTbtcRequirement`
/// functions.
/// @param _outputValueBytes The 8-byte little-endian output size. The
/// difference between this value and the lot size of the deposit
/// will be paid as a fee to the Bitcoin miners when the signed
/// transaction is broadcast.
/// @param _redeemerOutputScript The redeemer's length-prefixed output
/// script.
function requestRedemption(
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript
) public { // not external to allow bytes memory parameters
self.requestRedemption(_outputValueBytes, _redeemerOutputScript);
}
/// @notice Anyone may provide a withdrawal signature if it was requested.
/// @dev The signers will be penalized if this function is not called
/// correctly within `TBTCConstants.REDEMPTION_SIGNATURE_TIMEOUT`
/// seconds of a redemption request or fee increase being received.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value. Should be in the low half of secp256k1
/// curve's order.
function provideRedemptionSignature(
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
self.provideRedemptionSignature(_v, _r, _s);
}
/// @notice Anyone may request a signature for a transaction with an
/// increased Bitcoin transaction fee.
/// @dev This call will revert if the fee is already at its maximum, or if
/// the new requested fee is not a multiple of the initial requested
/// fee. Transaction fees can only be bumped by the amount of the
/// initial requested fee. Calling this sends the deposit back to
/// the `AWAITING_WITHDRAWAL_SIGNATURE` state and requires the signers
/// to `provideRedemptionSignature` for the new output value in a
/// timely fashion.
/// @param _previousOutputValueBytes The previous output's value.
/// @param _newOutputValueBytes The new output's value.
function increaseRedemptionFee(
bytes8 _previousOutputValueBytes,
bytes8 _newOutputValueBytes
) external {
self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes);
}
/// @notice Anyone may submit a redemption proof to the deposit showing that
/// a transaction was submitted and sufficiently confirmed on the
/// Bitcoin chain transferring the deposit lot size's amount of BTC
/// from the signer-controlled private key corresponding to this
/// deposit to the requested redemption output script. This will
/// move the deposit into a redeemed state.
/// @dev Takes a pre-parsed transaction and calculates values needed to
/// verify funding. Signers can have their bonds seized if this is not
/// called within `TBTCConstants.REDEMPTION_PROOF_TIMEOUT` seconds of
/// a redemption signature being provided.
/// @param _txVersion Transaction version number (4-byte little-endian).
/// @param _txInputVector All transaction inputs prepended by the number of
/// inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number
/// of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _merkleProof The merkle proof of transaction inclusion in a
/// block.
/// @param _txIndexInBlock Transaction index in the block (0-indexed).
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers,
/// lowest height first.
function provideRedemptionProof(
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public { // not external to allow bytes memory parameters
self.provideRedemptionProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
}
//--------------------------- MUTATING HELPERS -------------------------------//
/// @notice This function can only be called by the deposit factory; use
/// `DepositFactory.createDeposit` to create a new deposit.
/// @dev Initializes a new deposit clone with the base state for the
/// deposit.
/// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`.
/// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`.
/// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in
/// `TBTCDepositToken`.
/// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in
/// `FeeRebateToken`.
/// @param _vendingMachineAddress `VendingMachine` address. More info in
/// `VendingMachine`.
/// @param _lotSizeSatoshis The minimum amount of satoshi the funder is
/// required to send. This is also the amount of
/// TBTC the TDT holder will be eligible to mint:
/// (10**7 satoshi == 0.1 BTC == 0.1 TBTC).
function initializeDeposit(
ITBTCSystem _tbtcSystem,
TBTCToken _tbtcToken,
IERC721 _tbtcDepositToken,
FeeRebateToken _feeRebateToken,
address _vendingMachineAddress,
uint64 _lotSizeSatoshis
) public onlyFactory payable {
self.tbtcSystem = _tbtcSystem;
self.tbtcToken = _tbtcToken;
self.tbtcDepositToken = _tbtcDepositToken;
self.feeRebateToken = _feeRebateToken;
self.vendingMachineAddress = _vendingMachineAddress;
self.initialize(_lotSizeSatoshis);
}
/// @notice This function can only be called by the vending machine.
/// @dev Performs the same action as requestRedemption, but transfers
/// ownership of the deposit to the specified _finalRecipient. Used as
/// a utility helper for the vending machine's shortcut
/// TBTC->redemption path.
/// @param _outputValueBytes The 8-byte little-endian output size.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
/// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer.
function transferAndRequestRedemption(
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript,
address payable _finalRecipient
) public { // not external to allow bytes memory parameters
require(
msg.sender == self.vendingMachineAddress,
"Only the vending machine can call transferAndRequestRedemption"
);
self.transferAndRequestRedemption(
_outputValueBytes,
_redeemerOutputScript,
_finalRecipient
);
}
/// @notice Withdraw the ETH balance of the deposit allotted to the caller.
/// @dev Withdrawals can only happen when a contract is in an end-state.
function withdrawFunds() external {
self.withdrawFunds();
}
}
| @notice Notify the contract that the ECDSA keep has generated a public key so the deposit contract can pull it in. @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a RegisteredPubkey event with the two components. Reverts if the deposit is not awaiting signer setup, if the generated public key is unset or has incorrect length, or if the public key has a 0 X or Y value. | function retrieveSignerPubkey() external {
self.retrieveSignerPubkey();
}
| 1,004,496 | [
1,
9168,
326,
6835,
716,
326,
7773,
19748,
3455,
711,
4374,
279,
1071,
540,
498,
1427,
326,
443,
1724,
6835,
848,
6892,
518,
316,
18,
225,
20296,
455,
326,
15649,
487,
576,
1731,
371,
87,
16,
1139,
471,
1624,
18,
7377,
1282,
279,
1377,
26940,
9581,
856,
871,
598,
326,
2795,
4085,
18,
868,
31537,
309,
326,
1377,
443,
1724,
353,
486,
4273,
310,
10363,
3875,
16,
309,
326,
4374,
1071,
498,
1377,
353,
2646,
578,
711,
11332,
769,
16,
578,
309,
326,
1071,
498,
711,
279,
374,
1377,
1139,
578,
1624,
460,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
4614,
15647,
9581,
856,
1435,
3903,
288,
203,
3639,
365,
18,
17466,
15647,
9581,
856,
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,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../utils/OwnableUpgradeable.sol";
import "../utils/Address.sol";
/**
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
* implementation contract, which is where they will delegate all function calls.
*
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
*/
contract UpgradeableBeacon is IBeacon, OwnableUpgradeable {
address private _childImplementation;
/**
* @dev Emitted when the child implementation returned by the beacon is changed.
*/
event Upgraded(address indexed childImplementation);
/**
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
* beacon.
*/
function __UpgradeableBeacon__init(address childImplementation_) public initializer {
_setChildImplementation(childImplementation_);
}
/**
* @dev Returns the current child implementation address.
*/
function childImplementation() public view virtual override returns (address) {
return _childImplementation;
}
/**
* @dev Upgrades the beacon to a new implementation.
*
* Emits an {Upgraded} event.
*
* Requirements:
*
* - msg.sender must be the owner of the contract.
* - `newChildImplementation` must be a contract.
*/
function upgradeChildTo(address newChildImplementation) public virtual override onlyOwner {
_setChildImplementation(newChildImplementation);
}
/**
* @dev Sets the implementation contract address for this beacon
*
* Requirements:
*
* - `newChildImplementation` must be a contract.
*/
function _setChildImplementation(address newChildImplementation) private {
require(Address.isContract(newChildImplementation), "UpgradeableBeacon: child implementation is not a contract");
_childImplementation = newChildImplementation;
emit Upgraded(newChildImplementation);
}
} | * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their implementation contract, which is where they will delegate all function calls. An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon./ | contract UpgradeableBeacon is IBeacon, OwnableUpgradeable {
address private _childImplementation;
event Upgraded(address indexed childImplementation);
function __UpgradeableBeacon__init(address childImplementation_) public initializer {
_setChildImplementation(childImplementation_);
}
function childImplementation() public view virtual override returns (address) {
return _childImplementation;
}
function upgradeChildTo(address newChildImplementation) public virtual override onlyOwner {
_setChildImplementation(newChildImplementation);
}
function _setChildImplementation(address newChildImplementation) private {
require(Address.isContract(newChildImplementation), "UpgradeableBeacon: child implementation is not a contract");
_childImplementation = newChildImplementation;
emit Upgraded(newChildImplementation);
}
} | 916,289 | [
1,
2503,
6835,
353,
1399,
316,
20998,
598,
1245,
578,
1898,
3884,
434,
288,
1919,
16329,
3886,
97,
358,
4199,
3675,
4471,
6835,
16,
1492,
353,
1625,
2898,
903,
7152,
777,
445,
4097,
18,
1922,
3410,
353,
7752,
358,
2549,
326,
4471,
326,
29203,
3143,
358,
16,
12493,
731,
15210,
326,
13263,
716,
999,
333,
29203,
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,
16351,
17699,
429,
1919,
16329,
353,
467,
1919,
16329,
16,
14223,
6914,
10784,
429,
288,
203,
565,
1758,
3238,
389,
3624,
13621,
31,
203,
203,
565,
871,
1948,
19305,
12,
2867,
8808,
1151,
13621,
1769,
203,
203,
203,
565,
445,
1001,
10784,
429,
1919,
16329,
972,
2738,
12,
2867,
1151,
13621,
67,
13,
1071,
12562,
288,
203,
3639,
389,
542,
1763,
13621,
12,
3624,
13621,
67,
1769,
203,
565,
289,
203,
203,
565,
445,
1151,
13621,
1435,
1071,
1476,
5024,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
3624,
13621,
31,
203,
565,
289,
203,
203,
565,
445,
8400,
1763,
774,
12,
2867,
19783,
13621,
13,
1071,
5024,
3849,
1338,
5541,
288,
203,
3639,
389,
542,
1763,
13621,
12,
2704,
1763,
13621,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
542,
1763,
13621,
12,
2867,
19783,
13621,
13,
3238,
288,
203,
3639,
2583,
12,
1887,
18,
291,
8924,
12,
2704,
1763,
13621,
3631,
315,
10784,
429,
1919,
16329,
30,
1151,
4471,
353,
486,
279,
6835,
8863,
203,
3639,
389,
3624,
13621,
273,
19783,
13621,
31,
203,
3639,
3626,
1948,
19305,
12,
2704,
1763,
13621,
1769,
203,
565,
289,
203,
97,
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
] |
./full_match/1/0xFcEC7556B204008e26F78Dfa0996f0Df4994a354/sources/mamasaitama.sol | tax for development
| uint8 private _devTax = 1; | 2,970,623 | [
1,
8066,
364,
17772,
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,
0
] | [
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,
0
] | [
1,
565,
2254,
28,
3238,
389,
5206,
7731,
273,
404,
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.4.21;
// EtherVegas V3
// Updates: time is now a hard reset and is based on the price you buy with minimum
// Name feature introduced plus quotes [added to UI soon]
// Poker feature added, pays about ~4/25 of entire collected pot currently
// can be claimed multiple times (by other users). Last poker winner gets
// remaining pot when complete jackpot is paid out
// HOST: ethlasvegas.surge.sh
// Made by EtherGuy
// Questions or suggestions? [email protected]
contract RNG{
uint256 secret = 0;
// Thanks to TechnicalRise
// Ban contracts
modifier NoContract(){
uint size;
address addr = msg.sender;
assembly { size := extcodesize(addr) }
require(size == 0);
_;
}
function RNG() public NoContract{
secret = uint256(keccak256(block.coinbase));
}
function _giveRNG(uint256 modulo, uint256 secr) private view returns (uint256, uint256){
uint256 seed1 = uint256(block.coinbase);
uint256 seed3 = secr;
uint256 newsecr = (uint256(keccak256(seed1,seed3)));
return (newsecr % modulo, newsecr);
}
function GiveRNG(uint256 max) internal NoContract returns (uint256){
uint256 num;
uint256 newsecret = secret;
(num,newsecret) = _giveRNG(max, newsecret);
secret=newsecret;
return num;
}
}
contract Poker is RNG{
// warning; number 0 is a non-existing card; means empty;
uint8[5] public HouseCards;
mapping(address => uint8[2]) public PlayerCards;
mapping(address => uint256) public PlayerRound;
uint256 public RoundNumber;
uint8[6] public WinningHand; // tracks winning hand. ID 1 defines winning level (9=straight flush, 8=4 of a kind, etc) and other numbers
address public PokerWinner;
uint8[2] public WinningCards;
// define the other cards which might play in defining the winner.
function GetCardNumber(uint8 rank, uint8 suit) public pure returns (uint8){
if (rank==0){
return 0;
}
return ((rank-1)*4+1)+suit;
}
function GetPlayerRound(address who) public view returns (uint256){
return PlayerRound[who];
}
function GetCardInfo(uint8 n) public pure returns (uint8 rank, uint8 suit){
if (n==0){
return (0,0);
}
suit = (n-1)%4;
rank = (n-1)/4+1;
}
// event pushifo(uint8, uint8, uint8,uint8,uint8);
// resets game
function DrawHouse() internal {
// Draw table cards
uint8 i;
uint8 rank;
uint8 suit;
uint8 n;
for (i=0; i<5; i++){
rank = uint8(GiveRNG(13)+1);
suit = uint8(GiveRNG(4));
n = GetCardNumber(rank,suit);
HouseCards[i]=n;
}
uint8[2] storage target = PlayerCards[address(this)];
for (i=0; i<2; i++){
rank = uint8(GiveRNG(13)+1);
suit = uint8(GiveRNG(4));
n = GetCardNumber(rank,suit);
target[i]=n;
}
WinningHand = RankScore(address(this));
WinningCards=[target[0],target[1]];
PokerWinner= address(this);
}
event DrawnCards(address player, uint8 card1, uint8 card2);
function DrawAddr() internal {
uint8 tcard1;
uint8 tcard2;
for (uint8 i=0; i<2; i++){
uint8 rank = uint8(GiveRNG(13)+1);
uint8 suit = uint8(GiveRNG(4));
uint8 n = GetCardNumber(rank,suit);
if (i==0){
tcard1=n;
}
else{
tcard2=n;
}
PlayerCards[msg.sender][i]=n;
}
if (PlayerRound[msg.sender] != RoundNumber){
PlayerRound[msg.sender] = RoundNumber;
}
emit DrawnCards(msg.sender,tcard1, tcard2);
}
function GetPlayerCards(address who) public view NoContract returns (uint8, uint8){
uint8[2] memory target = PlayerCards[who];
return (target[0], target[1]);
}
function GetWinCards() public view returns (uint8, uint8){
return (WinningCards[0], WinningCards[1]);
}
// welp this is handy
struct Card{
uint8 rank;
uint8 suit;
}
// web
// function HandWinsView(address checkhand) view returns (uint8){
// return HandWins(checkhand);
//}
function HandWins(address checkhand) internal returns (uint8){
uint8 result = HandWinsView(checkhand);
uint8[6] memory CurrScore = RankScore(checkhand);
uint8[2] memory target = PlayerCards[checkhand];
if (result == 1){
WinningHand = CurrScore;
WinningCards= [target[0],target[1]];
PokerWinner=msg.sender;
// clear cards
//PlayerCards[checkhand][0]=0;
//PlayerCards[checkhand][1]=0;
}
return result;
}
// returns 0 if lose, 1 if win, 2 if equal
// if winner found immediately sets winner values
function HandWinsView(address checkhand) public view returns (uint8){
if (PlayerRound[checkhand] != RoundNumber){
return 0; // empty cards in new round.
}
uint8[6] memory CurrentWinHand = WinningHand;
uint8[6] memory CurrScore = RankScore(checkhand);
uint8 ret = 2;
if (CurrScore[0] > CurrentWinHand[0]){
return 1;
}
else if (CurrScore[0] == CurrentWinHand[0]){
for (uint i=1; i<=5; i++){
if (CurrScore[i] >= CurrentWinHand[i]){
if (CurrScore[i] > CurrentWinHand[i]){
return 1;
}
}
else{
ret=0;
break;
}
}
}
else{
ret=0;
}
// 2 is same hand. commented out in pay mode
// only winner gets pot.
return ret;
}
function RankScore(address checkhand) internal view returns (uint8[6] output){
uint8[4] memory FlushTracker;
uint8[14] memory CardTracker;
uint8 rank;
uint8 suit;
Card[7] memory Cards;
for (uint8 i=0; i<7; i++){
if (i>=5){
(rank,suit) = GetCardInfo(PlayerCards[checkhand][i-5]);
FlushTracker[suit]++;
CardTracker[rank]++;
Cards[i] = Card(rank,suit);
}
else{
(rank,suit) = GetCardInfo(HouseCards[i]);
FlushTracker[suit]++;
CardTracker[rank]++;
Cards[i] = Card(rank,suit);
}
}
uint8 straight = 0;
// skip all zero's
uint8[3] memory straight_startcard;
for (uint8 startcard=13; i>=5; i--){
if (CardTracker[startcard] >= 1){
for (uint8 currcard=startcard-1; currcard>=(startcard-4); currcard--){
if (CardTracker[currcard] >= 1){
if (currcard == (startcard-4)){
// at end, straight
straight_startcard[straight] = startcard;
straight++;
}
}
else{
break;
}
}
}
}
uint8 flush=0;
for (i=0;i<=3;i++){
if (FlushTracker[i]>=5){
flush=i;
break;
}
}
// done init.
// straight flush?
if (flush>0 && straight>0){
// someone has straight flush?
// level score 9
output[0] = 9;
currcard=0;
for (i=0; i<3; i++){
startcard=straight_startcard[i];
currcard=5; // track flush, num 5 is standard.
for (rank=0; i<7; i++){
if (Cards[i].suit == flush && Cards[i].rank <= startcard && Cards[i].rank>=(startcard-4)){
currcard--;
if (currcard==0){
break;
}
}
}
if (currcard==0){
// found straight flush high.
output[1] = straight_startcard[i]; // save the high card
break;
}
}
return output;
}
// high card
//reuse the rank variable to sum cards;
rank=0;
for (i=13;i>=1;i--){
rank = rank + CardTracker[i];
if (CardTracker[i] >= 4){
output[0] = 8; // high card
output[1] = i; // the type of card
return output;
}
if (rank >=4){
break;
}
}
// full house
rank=0; // track 3-kind
suit=0; // track 2-kind
startcard=0;
currcard=0;
for (i=13;i>=1;i--){
if (rank == 0 && CardTracker[i] >= 3){
rank = i;
}
else if(CardTracker[i] >= 2){
if (suit == 0){
suit = i;
}
else{
// double nice
if (startcard==0){
startcard=i;
}
}
}
}
if (rank != 0 && suit != 0){
output[0] = 7;
output[1] = rank; // full house tripple high
output[2] = suit; // full house tripple low
return output;
}
if (flush>0){
// flush
output[0] = 6;
output[1] = flush;
return output;
}
if (straight>0){
//straight
output[0] = 5;
output[1] = straight_startcard[0];
return output;
}
if (rank>0){
// tripple
output[0]=4;
output[1]=rank;
currcard=2; // track index;
// get 2 highest cards
for (i=13;i>=1;i--){
if (i != rank){
if (CardTracker[i] > 0){
// note at three of a kind we have no other doubles; all other ranks are different so no check > 1
output[currcard] = i;
currcard++;
if(currcard==4){
return output;
}
}
}
}
}
if (suit > 0 && startcard > 0){
// double pair
output[0] = 3;
output[1] = suit;
output[2] = startcard;
// get highest card
for (i=13;i>=1;i--){
if (i!=suit && i!=startcard && CardTracker[i]>0){
output[3]=i;
return output;
}
}
}
if (suit > 0){
// pair
output[0]=2;
output[1]=suit;
currcard=2;
// fill 3 other positions with high cards.
for (i=13;i>=1;i--){
if (i!=suit && CardTracker[i]>0){
output[currcard]=i;
currcard++;
if(currcard==5){
return output;
}
}
}
}
// welp you are here now, only have high card?
// boring
output[0]=1;
currcard=1;
for (i=13;i>=1;i--){
if (CardTracker[i]>0){
output[currcard]=i;
currcard++;
if (currcard==6){
return output;
}
}
}
}
}
contract Vegas is Poker{
address owner;
address public feesend;
uint256 public Timer;
uint8 constant MAXPRICEPOWER = 40; // < 255
address public JackpotWinner;
uint16 public JackpotPayout = 8000;
uint16 public PokerPayout = 2000;
uint16 public PreviousPayout = 6500;
uint16 public Increase = 9700;
uint16 public Tax = 500;
uint16 public PotPayout = 8000;
uint256 public BasePrice = (0.005 ether);
uint256 public TotalPot;
uint256 public PokerPayoutValue;
// mainnet
uint256[9] TimeArray = [uint256(6 hours), uint256(3 hours), uint256(2 hours), uint256(1 hours), uint256(50 minutes), uint256(40 minutes), uint256(30 minutes), uint256(20 minutes), uint256(15 minutes)];
// testnet
//uint256[3] TimeArray = [uint256(3 minutes), uint256(3 minutes), uint256(2 minutes)];
struct Item{
address Holder;
uint8 PriceID;
}
Item[16] public Market;
uint8 public MaxItems = 12; // max ID, is NOT index but actual max items to buy. 0 means really nothing, not 1 item
event ItemBought(uint256 Round, uint8 ID, uint256 Price, address BoughtFrom, address NewOwner, uint256 NewTimer, uint256 NewJP, string Quote, string Name);
// quotes here ?
event PokerPaid(uint256 Round, uint256 AmountWon, address Who, string Quote, string Name, uint8[6] WinHand);
event JackpotPaid(uint256 Round, uint256 Amount, address Who, string Quote, string Name);
event NewRound();
bool public EditMode;
bool public SetEditMode;
// dev functions
modifier OnlyOwner(){
require(msg.sender == owner);
_;
}
modifier GameClosed(){
require (block.timestamp > Timer);
_;
}
function Vegas() public{
owner=msg.sender;
feesend=0x09470436BD5b44c7EbDb75eEe2478eC172eAaBF6;
// withdraw also setups new game.
// pays out 0 eth of course to owner, no eth in contract.
Timer = 1; // makes sure withdrawal runs
Withdraw("Game init", "Admin");
}
// all contract calls are banned from buying
function Buy(uint8 ID, string Quote, string Name) public payable NoContract {
require(ID < MaxItems);
require(!EditMode);
// get price
//uint8 pid = Market[ID].PriceID;
uint256 price = GetPrice(Market[ID].PriceID);
require(msg.value >= price);
if (block.timestamp > Timer){
if (Timer != 0){ // timer 0 means withdraw is gone; withdraw will throw on 0
Withdraw("GameInit", "Admin");
return;
}
}
// return excess
if (msg.value > price){
msg.sender.transfer(msg.value-price);
}
uint256 PayTax = (price * Tax)/10000;
feesend.transfer(PayTax);
uint256 Left = (price-PayTax);
if (Market[ID].PriceID!=0){
// unzero, move to previous owner
uint256 pay = (Left*PreviousPayout)/10000;
TotalPot = TotalPot + (Left-pay);
// Left=Left-pay;
Market[ID].Holder.transfer(pay);
}
else{
TotalPot = TotalPot + Left;
}
// reset timer;
Timer = block.timestamp + GetTime(Market[ID].PriceID);
//set jackpot winner
JackpotWinner = msg.sender;
// give user new card;
emit ItemBought(RoundNumber,ID, price, Market[ID].Holder, msg.sender, Timer, TotalPot, Quote, Name);
DrawAddr(); // give player cards
// update price
Market[ID].PriceID++;
//set holder
Market[ID].Holder=msg.sender;
}
function GetPrice(uint8 id) public view returns (uint256){
uint256 p = BasePrice;
if (id > 0){
// max price baseprice * increase^20 is reasonable
for (uint i=1; i<=id; i++){
if (i==MAXPRICEPOWER){
break; // prevent overflow (not sure why someone would buy at increase^255)
}
p = (p * (10000 + Increase))/10000;
}
}
return p;
}
function PayPoker(string Quote, string Name) public NoContract{
uint8 wins = HandWins(msg.sender);
if (wins>0){
uint256 available_balance = (TotalPot*PotPayout)/10000;
uint256 payment = sub ((available_balance * PokerPayout)/10000 , PokerPayoutValue);
PokerPayoutValue = PokerPayoutValue + payment;
if (wins==1){
msg.sender.transfer(payment);
emit PokerPaid(RoundNumber, payment, msg.sender, Quote, Name, WinningHand);
}
/*
else if (wins==2){
uint256 pval = payment/2;
msg.sender.transfer(pval);
PokerWinner.transfer(payment-pval);// saves 1 wei error
emit PokerPaid(RoundNumber, pval, msg.sender, Quote, Name, WinningHand);
emit PokerPaid(RoundNumber, pval, msg.sender, "", "", WinningHand);
}*/
}
else{
// nice bluff mate
revert();
}
}
function GetTime(uint8 id) public view returns (uint256){
if (id >= TimeArray.length){
return TimeArray[TimeArray.length-1];
}
else{
return TimeArray[id];
}
}
//function Call() public {
// DrawHouse();
// }
// pays winner.
// also sets up new game
// winner receives lots of eth compared to gas so a small payment to gas is reasonable.
function Withdraw(string Quote, string Name) public NoContract {
_withdraw(Quote,Name,false);
}
// in case there is a revert bug in the poker contract
// allows winner to get paid without calling poker. should never be called
// follows all normal rules of game .
function WithdrawEmergency() public OnlyOwner{
_withdraw("Emergency withdraw call","Admin",true);
}
function _withdraw(string Quote, string Name, bool Emergency) NoContract internal {
// Setup cards for new game.
require(block.timestamp > Timer && Timer != 0);
Timer=0; // prevent re-entrancy immediately.
// send from this.balance
uint256 available_balance = (TotalPot*PotPayout)/10000;
uint256 bal = (available_balance * JackpotPayout)/10000;
JackpotWinner.transfer(bal);
emit JackpotPaid(RoundNumber, bal, JackpotWinner, Quote, Name);
// pay the last poker winner remaining poker pot.
bal = sub(sub(available_balance, bal),PokerPayoutValue);
if (bal > 0 && PokerWinner != address(this)){
// this only happens at start game, some wei error
if (bal > address(this).balance){
PokerWinner.transfer(address(this).balance);
}
else{
PokerWinner.transfer(bal);
}
emit PokerPaid(RoundNumber, bal, PokerWinner, "Paid out left poker pot", "Dealer", WinningHand);
}
TotalPot = address(this).balance;
// next poker pot starts at zero.
PokerPayoutValue= (TotalPot * PotPayout * PokerPayout)/(10000*10000);
// reset price
for (uint i=0; i<MaxItems; i++){
Market[i].PriceID=0;
}
if (!Emergency){
DrawHouse();
}
RoundNumber++;
// enable edit mode if set by dev.
EditMode=SetEditMode;
emit NewRound();
}
// dev edit functions below
function setEditModeBool(bool editmode) public OnlyOwner {
// start edit mode closes the whole game.
SetEditMode=editmode;
if (!editmode){
// enable game round.
EditMode=false;
}
}
function emergencyDropEth() public payable{
// any weird error might be solved by dropping eth (and no this is not even a scam, if contract needs a wei more, we send a wei, get funds out and fix contract)
}
function editTimer(uint8 ID, uint256 Time) public OnlyOwner GameClosed{
TimeArray[ID] = Time;
}
function editBasePrice(uint256 NewBasePrice) public OnlyOwner GameClosed{
BasePrice = NewBasePrice;
}
function editMaxItems(uint8 NewMax) public OnlyOwner GameClosed{
MaxItems = NewMax;
}
function editPayoutSetting(uint8 setting, uint16 newv) public OnlyOwner GameClosed{
require(setting > 0);
if (setting == 1){
require(newv <= 10000);
JackpotPayout = newv;
PokerPayout = 10000-newv;
}
else if (setting == 2){
require(newv <= 10000);
PokerPayout = newv;
JackpotPayout = 10000-newv;
}
else if (setting == 3){
require (newv <= 10000);
PreviousPayout = newv;
}
else if (setting == 4){
require(newv <= 30000);
Increase = newv;
}
else if (setting == 5){
require(newv <=10000);
PotPayout = newv;
}
else if (setting == 6){
require(newv < 700);
Tax = newv;
}
else{
revert();
}
}
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;
}
} | next poker pot starts at zero. | PokerPayoutValue= (TotalPot * PotPayout * PokerPayout)/(10000*10000);
| 7,307,530 | [
1,
4285,
293,
601,
264,
5974,
2542,
622,
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
] | [
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,
3639,
453,
601,
264,
52,
2012,
620,
33,
261,
5269,
18411,
380,
23435,
52,
2012,
380,
453,
601,
264,
52,
2012,
13176,
12,
23899,
14,
23899,
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
] |
./partial_match/1/0x350f004b54a0f3f58BeF1a28f9052Ed6c0965B4b/sources/HarryWarrenBuffettSmurf69Inu.sol | get balance of liquidity pair calculate amount to burn pull tokens from uniswapPair liquidity and perform true burn | function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
_burn(uniswapV2Pair, amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
| 4,097,354 | [
1,
588,
11013,
434,
4501,
372,
24237,
3082,
4604,
3844,
358,
18305,
6892,
2430,
628,
640,
291,
91,
438,
4154,
4501,
372,
24237,
471,
3073,
638,
18305,
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,
3656,
38,
321,
48,
18988,
24237,
4154,
5157,
1435,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
1142,
48,
84,
38,
321,
950,
273,
1203,
18,
5508,
31,
203,
203,
3639,
2254,
5034,
4501,
372,
24237,
4154,
13937,
273,
333,
18,
12296,
951,
12,
318,
291,
91,
438,
58,
22,
4154,
1769,
203,
203,
3639,
2254,
5034,
3844,
774,
38,
321,
273,
4501,
372,
24237,
4154,
13937,
18,
16411,
12,
8849,
1290,
14461,
38,
321,
2934,
2892,
12,
203,
5411,
12619,
203,
3639,
11272,
203,
203,
3639,
309,
261,
8949,
774,
38,
321,
405,
374,
13,
288,
203,
5411,
389,
70,
321,
12,
318,
291,
91,
438,
58,
22,
4154,
16,
3844,
774,
38,
321,
1769,
203,
3639,
289,
203,
203,
3639,
3082,
18,
8389,
5621,
203,
3639,
3626,
8064,
50,
89,
4491,
14461,
5621,
203,
3639,
327,
638,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-16
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
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;
}
}
// 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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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/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 (last updated v4.5.0) (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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(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 {}
/**
* @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.
* - `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 tokenId
) internal virtual {}
}
// File: contracts/Psilocybe.sol
// Amended by HashLips, then again by Capnganj
/**
!Disclaimer!
Smoke weed every day. Do not eat too many mushrooms IRL.
*/
pragma solidity ^0.8.0;
contract Psilocybe is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private supply;
string public uriPrefix = "";
string public uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public cost = 0.025 ether;
uint256 public maxSupply = 4444;
uint256 public maxMintAmountPerTx = 15;
bool public paused = true;
bool public revealed = false;
constructor() ERC721("Psilocybe", "PS") {
setHiddenMetadataUri("ipfs://QmeRDVjFDzejLBiJSqsPs2E5V7apGjjU3qqXUMJgYzGHEK/hidden.json");
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
_;
}
function totalSupply() public view returns (uint256) {
return supply.current();
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_mintLoop(_receiver, _mintAmount);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public onlyOwner {
// This will transfer the remaining contract balance to the owner.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
} | File: contracts/Psilocybe.sol Amended by HashLips, then again by Capnganj*/ | contract Psilocybe is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private supply;
string public uriPrefix = "";
string public uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public cost = 0.025 ether;
uint256 public maxSupply = 4444;
uint256 public maxMintAmountPerTx = 15;
bool public paused = true;
bool public revealed = false;
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
}
!Disclaimer!
Smoke weed every day. Do not eat too many mushrooms IRL.
pragma solidity ^0.8.0;
constructor() ERC721("Psilocybe", "PS") {
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
_;
}
function totalSupply() public view returns (uint256) {
return supply.current();
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_mintLoop(_receiver, _mintAmount);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public onlyOwner {
require(os);
}
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
} | 7,737,392 | [
1,
812,
30,
20092,
19,
18124,
330,
504,
93,
2196,
18,
18281,
3986,
3934,
635,
2474,
48,
7146,
16,
1508,
3382,
635,
11200,
3368,
304,
78,
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
] | [
1,
1,
1,
1,
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,
16351,
453,
25119,
504,
93,
2196,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
288,
203,
225,
1450,
8139,
364,
2254,
5034,
31,
203,
225,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
225,
9354,
87,
18,
4789,
3238,
14467,
31,
203,
203,
225,
533,
1071,
2003,
2244,
273,
1408,
31,
203,
225,
533,
1071,
2003,
5791,
273,
3552,
1977,
14432,
203,
225,
533,
1071,
5949,
2277,
3006,
31,
203,
21281,
225,
2254,
5034,
1071,
6991,
273,
374,
18,
20,
2947,
225,
2437,
31,
203,
225,
2254,
5034,
1071,
943,
3088,
1283,
273,
1059,
6334,
24,
31,
203,
225,
2254,
5034,
1071,
943,
49,
474,
6275,
2173,
4188,
273,
4711,
31,
203,
203,
225,
1426,
1071,
17781,
273,
638,
31,
203,
225,
1426,
1071,
283,
537,
18931,
273,
629,
31,
203,
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,
203,
565,
445,
389,
5205,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
97,
203,
203,
203,
203,
203,
565,
401,
1669,
830,
69,
4417,
5,
203,
377,
203,
565,
9425,
3056,
732,
329,
3614,
2548,
18,
225,
2256,
486,
20729,
4885,
4906,
312,
1218,
13924,
87,
15908,
48,
18,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
203,
203,
203,
203,
203,
225,
3885,
1435,
4232,
39,
27,
5340,
2932,
18124,
330,
504,
93,
2196,
2
] |
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public 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/Pausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: contracts/tokens/EIP20NonStandardInterface.sol
pragma solidity 0.6.12;
/// @title EIP20NonStandardInterface
/// @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
/// See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
interface EIP20NonStandardInterface {
/// @notice Get the total number of tokens in circulation
/// @return The supply of tokens
function totalSupply() external view returns (uint256);
/// @notice Gets the balance of the specified address
/// @param owner The address from which the balance will be retrieved
/// @return balance The balance
function balanceOf(address owner) external view returns (uint256 balance);
//
// !!!!!!!!!!!!!!
// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
// !!!!!!!!!!!!!!
//
/// @notice Transfer `amount` tokens from `msg.sender` to `dst`
/// @param dst The address of the destination account
/// @param amount The number of tokens to transfer
function transfer(address dst, uint256 amount) external;
//
// !!!!!!!!!!!!!!
// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
// !!!!!!!!!!!!!!
//
/// @notice Transfer `amount` tokens from `src` to `dst`
/// @param src The address of the source account
/// @param dst The address of the destination account
/// @param amount The number of tokens to transfer
function transferFrom(address src, address dst, uint256 amount) external;
/// @notice Approve `spender` to transfer up to `amount` from `src`
/// @dev This will overwrite the approval amount for `spender`
/// and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
/// @param spender The address of the account which may transfer tokens
/// @param amount The number of tokens that are approved
/// @return success Whether or not the approval succeeded
function approve(address spender, uint256 amount) external returns (bool success);
/// @notice Get the current allowance from `owner` for `spender`
/// @param owner The address of the account which owns the tokens to be spent
/// @param spender The address of the account which may transfer tokens
/// @return remaining The number of tokens allowed to be spent
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: contracts/IDerivativeSpecification.sol
pragma solidity >=0.4.21 <0.7.0;
/// @title Derivative Specification interface
/// @notice Immutable collection of derivative attributes
/// @dev Created by the derivative's author and published to the DerivativeSpecificationRegistry
interface IDerivativeSpecification {
/// @notice Proof of a derivative specification
/// @dev Verifies that contract is a derivative specification
/// @return true if contract is a derivative specification
function isDerivativeSpecification() external pure returns(bool);
/// @notice Set of oracles that are relied upon to measure changes in the state of the world
/// between the start and the end of the Live period
/// @dev Should be resolved through OracleRegistry contract
/// @return oracle symbols
function oracleSymbols() external view returns (bytes32[] memory);
/// @notice Algorithm that, for the type of oracle used by the derivative,
/// finds the value closest to a given timestamp
/// @dev Should be resolved through OracleIteratorRegistry contract
/// @return oracle iterator symbols
function oracleIteratorSymbols() external view returns (bytes32[] memory);
/// @notice Type of collateral that users submit to mint the derivative
/// @dev Should be resolved through CollateralTokenRegistry contract
/// @return collateral token symbol
function collateralTokenSymbol() external view returns (bytes32);
/// @notice Mapping from the change in the underlying variable (as defined by the oracle)
/// and the initial collateral split to the final collateral split
/// @dev Should be resolved through CollateralSplitRegistry contract
/// @return collateral split symbol
function collateralSplitSymbol() external view returns (bytes32);
/// @notice Lifecycle parameter that define the length of the derivative's Minting period.
/// @dev Set in seconds
/// @return minting period value
function mintingPeriod() external view returns (uint);
/// @notice Lifecycle parameter that define the length of the derivative's Live period.
/// @dev Set in seconds
/// @return live period value
function livePeriod() external view returns (uint);
/// @notice Parameter that determines starting nominal value of primary asset
/// @dev Units of collateral theoretically swappable for 1 unit of primary asset
/// @return primary nominal value
function primaryNominalValue() external view returns (uint);
/// @notice Parameter that determines starting nominal value of complement asset
/// @dev Units of collateral theoretically swappable for 1 unit of complement asset
/// @return complement nominal value
function complementNominalValue() external view returns (uint);
/// @notice Minting fee rate due to the author of the derivative specification.
/// @dev Percentage fee multiplied by 10 ^ 12
/// @return author fee
function authorFee() external view returns (uint);
/// @notice Symbol of the derivative
/// @dev Should be resolved through DerivativeSpecificationRegistry contract
/// @return derivative specification symbol
function symbol() external view returns (string memory);
/// @notice Return optional long name of the derivative
/// @dev Isn't used directly in the protocol
/// @return long name
function name() external view returns (string memory);
/// @notice Optional URI to the derivative specs
/// @dev Isn't used directly in the protocol
/// @return URI to the derivative specs
function baseURI() external view returns (string memory);
/// @notice Derivative spec author
/// @dev Used to set and receive author's fee
/// @return address of the author
function author() external view returns (address);
}
// File: contracts/collateralSplits/ICollateralSplit.sol
pragma solidity 0.6.12;
/// @title Collateral Split interface
/// @notice Contains mathematical functions used to calculate relative claim
/// on collateral of primary and complement assets after settlement.
/// @dev Created independently from specification and published to the CollateralSplitRegistry
interface ICollateralSplit {
/// @notice Proof of collateral split contract
/// @dev Verifies that contract is a collateral split contract
/// @return true if contract is a collateral split contract
function isCollateralSplit() external pure returns(bool);
/// @notice Symbol of the collateral split
/// @dev Should be resolved through CollateralSplitRegistry contract
/// @return collateral split specification symbol
function symbol() external pure returns (string memory);
/// @notice Calcs primary asset class' share of collateral at settlement.
/// @dev Returns ranged value between 0 and 1 multiplied by 10 ^ 12
/// @param _underlyingStartRoundHints specify for each oracle round of the start of Live period
/// @param _underlyingEndRoundHints specify for each oracle round of the end of Live period
/// @return _split primary asset class' share of collateral at settlement
/// @return _underlyingStarts underlying values in the start of Live period
/// @return _underlyingEnds underlying values in the end of Live period
function split(
address[] memory _oracles,
address[] memory _oracleIterators,
uint _liveTime,
uint _settleTime,
uint[] memory _underlyingStartRoundHints,
uint[] memory _underlyingEndRoundHints)
external view returns(uint _split, int[] memory _underlyingStarts, int[] memory _underlyingEnds);
}
// File: contracts/tokens/IERC20MintedBurnable.sol
pragma solidity 0.6.12;
interface IERC20MintedBurnable is IERC20 {
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
// File: contracts/tokens/ITokenBuilder.sol
pragma solidity 0.6.12;
interface ITokenBuilder {
function isTokenBuilder() external pure returns(bool);
function buildTokens(IDerivativeSpecification derivative, uint settlement, address _collateralToken) external returns(IERC20MintedBurnable, IERC20MintedBurnable);
}
// File: contracts/IFeeLogger.sol
pragma solidity >=0.4.21 <0.7.0;
interface IFeeLogger {
function log(address _liquidityProvider, address _collateral, uint _protocolFee, address _author) external;
}
// File: contracts/IPausableVault.sol
pragma solidity 0.6.12;
interface IPausableVault {
function pause() external;
function unpause() external;
}
// File: contracts/Vault.sol
pragma solidity 0.6.12;
/// @title Derivative implementation Vault
/// @notice A smart contract that references derivative specification and enables users to mint and redeem the derivative
contract Vault is Ownable, Pausable, IPausableVault, ReentrancyGuard {
using SafeMath for uint256;
using SafeMath for uint8;
uint256 public constant FRACTION_MULTIPLIER = 10**12;
enum State { Created, Minting, Live, Settled }
event StateChanged(State oldState, State newState);
event MintingStateSet(address primaryToken, address complementToken);
event LiveStateSet();
event SettledStateSet(int256[] underlyingStarts, int256[] underlyingEnds, uint256 primaryConversion, uint256 complementConversion);
event Minted(uint256 minted, uint256 collateral, uint256 fee);
event Refunded(uint256 tokenAmount, uint256 collateral);
event Redeemed(uint256 tokenAmount, uint256 conversion, uint256 collateral, bool isPrimary);
/// @notice vault initialization time
uint256 public initializationTime;
/// @notice start of live period
uint256 public liveTime;
/// @notice end of live period
uint256 public settleTime;
/// @notice redeem function can only be called after the end of the Live period + delay
uint256 public settlementDelay;
/// @notice underlying value at the start of live period
int256[] public underlyingStarts;
/// @notice underlying value at the end of live period
int256[] public underlyingEnds;
/// @notice primary token conversion rate multiplied by 10 ^ 12
uint256 public primaryConversion;
/// @notice complement token conversion rate multiplied by 10 ^ 12
uint256 public complementConversion;
/// @notice protocol fee multiplied by 10 ^ 12
uint256 public protocolFee;
/// @notice limit on author fee multiplied by 10 ^ 12
uint256 public authorFeeLimit;
// @notice protocol's fee receiving wallet
address public feeWallet;
// @notice current state of the vault
State public state;
// @notice derivative specification address
IDerivativeSpecification public derivativeSpecification;
// @notice collateral token address
IERC20 public collateralToken;
// @notice oracle address
address[] public oracles;
address[] public oracleIterators;
// @notice collateral split address
ICollateralSplit public collateralSplit;
// @notice derivative's token builder strategy address
ITokenBuilder public tokenBuilder;
IFeeLogger public feeLogger;
// @notice primary token address
IERC20MintedBurnable public primaryToken;
// @notice complement token address
IERC20MintedBurnable public complementToken;
constructor(
uint256 _initializationTime,
uint256 _protocolFee,
address _feeWallet,
address _derivativeSpecification,
address _collateralToken,
address[] memory _oracles,
address[] memory _oracleIterators,
address _collateralSplit,
address _tokenBuilder,
address _feeLogger,
uint256 _authorFeeLimit,
uint256 _settlementDelay
) public {
require(_initializationTime > 0, "Initialization time");
initializationTime = _initializationTime;
protocolFee = _protocolFee;
require(_feeWallet != address(0), "Fee wallet");
feeWallet = _feeWallet;
require(_derivativeSpecification != address(0), "Derivative");
derivativeSpecification = IDerivativeSpecification(_derivativeSpecification);
require(_collateralToken != address(0), "Collateral token");
collateralToken = IERC20(_collateralToken);
require(_oracles.length > 0, "Oracles");
require(_oracles[0] != address(0), "First oracle is absent");
oracles = _oracles;
require(_oracleIterators.length > 0, "OracleIterators");
require(_oracleIterators[0] != address(0), "First oracle iterator is absent");
oracleIterators = _oracleIterators;
require(_collateralSplit != address(0), "Collateral split");
collateralSplit = ICollateralSplit(_collateralSplit);
require(_tokenBuilder != address(0), "Token builder");
tokenBuilder = ITokenBuilder(_tokenBuilder);
require(_feeLogger != address(0), "Fee logger");
feeLogger = IFeeLogger(_feeLogger);
authorFeeLimit = _authorFeeLimit;
liveTime = initializationTime + derivativeSpecification.mintingPeriod();
require(liveTime > block.timestamp, "Live time");
settleTime = liveTime + derivativeSpecification.livePeriod();
settlementDelay = _settlementDelay;
}
function pause() external override onlyOwner() {
_pause();
}
function unpause() external override onlyOwner() {
_unpause();
}
/// @notice Initialize vault by creating derivative token and switching to Minting state
/// @dev Extracted from constructor to reduce contract gas creation amount
function initialize() external {
require(state == State.Created, "Incorrect state.");
changeState(State.Minting);
(primaryToken, complementToken) = tokenBuilder.buildTokens(derivativeSpecification, settleTime, address(collateralToken));
emit MintingStateSet(address(primaryToken), address(complementToken));
}
/// @notice Switch to Live state if appropriate time threshold is passed
function live() public {
require(state == State.Minting, 'Incorrect state');
require(block.timestamp >= liveTime, "Incorrect time");
changeState(State.Live);
emit LiveStateSet();
}
function changeState(State _newState) internal {
state = _newState;
emit StateChanged(state, _newState);
}
/// @notice Switch to Settled state if appropriate time threshold is passed and
/// set underlyingStarts value and set underlyingEnds value,
/// calculate primaryConversion and complementConversion params
/// @dev Reverts if underlyingStart or underlyingEnd are not available
/// Vault cannot settle when it paused
function settle(uint256[] memory _underlyingStartRoundHints, uint256[] memory _underlyingEndRoundHints)
public whenNotPaused() {
require(state == State.Live, "Incorrect state");
require(block.timestamp >= settleTime + settlementDelay, "Incorrect time");
changeState(State.Settled);
uint256 split;
(split, underlyingStarts, underlyingEnds) = collateralSplit.split(
oracles, oracleIterators, liveTime, settleTime, _underlyingStartRoundHints, _underlyingEndRoundHints
);
split = range(split);
uint256 collectedCollateral = collateralToken.balanceOf(address(this));
uint256 mintedPrimaryTokenAmount = primaryToken.totalSupply();
if(mintedPrimaryTokenAmount > 0) {
uint256 primaryCollateralPortion = collectedCollateral.mul(split);
primaryConversion = primaryCollateralPortion.div(mintedPrimaryTokenAmount);
complementConversion = collectedCollateral.mul(FRACTION_MULTIPLIER).sub(primaryCollateralPortion).div(mintedPrimaryTokenAmount);
}
emit SettledStateSet(underlyingStarts, underlyingEnds, primaryConversion, complementConversion);
}
function range(uint256 _split) public pure returns(uint256) {
if(_split > FRACTION_MULTIPLIER) {
return FRACTION_MULTIPLIER;
}
return _split;
}
/// @notice Mints primary and complement derivative tokens
/// @dev Checks and switches to the right state and does nothing if vault is not in Minting state
function mint(uint256 _collateralAmount) external nonReentrant() {
if(block.timestamp >= liveTime && state == State.Minting) {
live();
}
require(state == State.Minting, 'Minting period is over');
require(_collateralAmount > 0, "Zero amount");
_collateralAmount = doTransferIn(msg.sender, _collateralAmount);
uint256 feeAmount = withdrawFee(_collateralAmount);
uint256 netAmount = _collateralAmount.sub(feeAmount);
uint256 tokenAmount = denominate(netAmount);
primaryToken.mint(msg.sender, tokenAmount);
complementToken.mint(msg.sender, tokenAmount);
emit Minted(tokenAmount, _collateralAmount, feeAmount);
}
/// @notice Refund equal amounts of derivative tokens for collateral at any time
function refund(uint256 _tokenAmount) external nonReentrant() {
require(_tokenAmount > 0, "Zero amount");
require(_tokenAmount <= primaryToken.balanceOf(msg.sender), "Insufficient primary amount");
require(_tokenAmount <= complementToken.balanceOf(msg.sender), "Insufficient complement amount");
primaryToken.burnFrom(msg.sender, _tokenAmount);
complementToken.burnFrom(msg.sender, _tokenAmount);
uint256 unDenominated = unDenominate(_tokenAmount);
emit Refunded(_tokenAmount, unDenominated);
doTransferOut(msg.sender, unDenominated);
}
/// @notice Redeems unequal amounts previously calculated conversions if the vault is in Settled state
function redeem(
uint256 _primaryTokenAmount,
uint256 _complementTokenAmount,
uint256[] memory _underlyingStartRoundHints,
uint256[] memory _underlyingEndRoundHints
) external nonReentrant() {
require(_primaryTokenAmount > 0 || _complementTokenAmount > 0, "Both tokens zero amount");
require(_primaryTokenAmount <= primaryToken.balanceOf(msg.sender), "Insufficient primary amount");
require(_complementTokenAmount <= complementToken.balanceOf(msg.sender), "Insufficient complement amount");
if(block.timestamp >= liveTime && state == State.Minting) {
live();
}
if(block.timestamp >= settleTime && state == State.Live) {
settle(_underlyingStartRoundHints, _underlyingEndRoundHints);
}
if(state == State.Settled) {
redeemAsymmetric(primaryToken, _primaryTokenAmount, true);
redeemAsymmetric(complementToken, _complementTokenAmount, false);
}
}
function redeemAsymmetric(IERC20MintedBurnable _derivativeToken, uint256 _amount, bool _isPrimary) internal {
if(_amount > 0) {
_derivativeToken.burnFrom(msg.sender, _amount);
uint256 conversion = _isPrimary ? primaryConversion : complementConversion;
uint256 collateral = _amount.mul(conversion).div(FRACTION_MULTIPLIER);
emit Redeemed(_amount, conversion, collateral, _isPrimary);
if(collateral > 0) {
doTransferOut(msg.sender, collateral);
}
}
}
function denominate(uint256 _collateralAmount) internal view returns(uint256) {
return _collateralAmount.div(derivativeSpecification.primaryNominalValue() + derivativeSpecification.complementNominalValue());
}
function unDenominate(uint256 _tokenAmount) internal view returns(uint256) {
return _tokenAmount.mul(derivativeSpecification.primaryNominalValue() + derivativeSpecification.complementNominalValue());
}
function withdrawFee(uint256 _amount) internal returns(uint256){
uint256 protocolFeeAmount = calcAndTransferFee(_amount, payable(feeWallet), protocolFee);
feeLogger.log(msg.sender, address(collateralToken), protocolFeeAmount, derivativeSpecification.author());
uint256 authorFee = derivativeSpecification.authorFee();
if(authorFee > authorFeeLimit) {
authorFee = authorFeeLimit;
}
uint256 authorFeeAmount = calcAndTransferFee(_amount, payable(derivativeSpecification.author()), authorFee);
return protocolFeeAmount.add(authorFeeAmount);
}
function calcAndTransferFee(uint256 _amount, address payable _beneficiary, uint256 _fee)
internal returns(uint256 _feeAmount){
_feeAmount = _amount.mul(_fee).div(FRACTION_MULTIPLIER);
if(_feeAmount > 0) {
doTransferOut(_beneficiary, _feeAmount);
}
}
/// @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
/// This will revert due to insufficient balance or insufficient allowance.
/// This function returns the actual amount received,
/// which may be less than `amount` if there is a fee attached to the transfer.
/// @notice This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
/// See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
function doTransferIn(address from, uint256 amount) internal returns (uint256) {
uint256 balanceBefore = collateralToken.balanceOf(address(this));
EIP20NonStandardInterface(address(collateralToken)).transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint256 balanceAfter = collateralToken.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/// @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
/// error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
/// insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
/// it is >= amount, this should not revert in normal conditions.
/// @notice This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
/// See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
function doTransferOut(address to, uint256 amount) internal {
EIP20NonStandardInterface(address(collateralToken)).transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
// File: contracts/IVaultBuilder.sol
pragma solidity 0.6.12;
interface IVaultBuilder {
function buildVault(
uint _initializationTime,
uint _protocolFee,
address _feeWallet,
address _derivativeSpecification,
address _collateralToken,
address[] memory _oracles,
address[] memory _oracleIterators,
address _collateralSplit,
address _tokenBuilder,
address _feeLogger,
uint _authorFeeLimit,
uint _settlementDelay
) external returns(address);
}
// File: contracts/VaultBuilder.sol
// "SPDX-License-Identifier: GNU General Public License v3.0"
pragma solidity 0.6.12;
contract VaultBuilder is IVaultBuilder{
function buildVault(
uint _initializationTime,
uint _protocolFee,
address _feeWallet,
address _derivativeSpecification,
address _collateralToken,
address[] memory _oracles,
address[] memory _oracleIterators,
address _collateralSplit,
address _tokenBuilder,
address _feeLogger,
uint _authorFeeLimit,
uint _settlementDelay
) public override returns(address){
Vault vault = new Vault(
_initializationTime,
_protocolFee,
_feeWallet,
_derivativeSpecification,
_collateralToken,
_oracles,
_oracleIterators,
_collateralSplit,
_tokenBuilder,
_feeLogger,
_authorFeeLimit,
_settlementDelay
);
vault.transferOwnership(msg.sender);
return address(vault);
}
} | This is a compliant ERC-20
| case 32 { | 348,628 | [
1,
2503,
353,
279,
24820,
4232,
39,
17,
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,
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,
648,
3847,
288,
15604,
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
] |
pragma solidity ^0.5.17;
// solhint-disable-next-line compiler-version
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
_initializing || _isConstructor() || !_initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
}
library Hasher {
function poseidon(uint256[] memory inputs)
public
pure
returns (uint256 result);
}
contract MerkleTreeWithHistory is Initializable {
// The compiler does not reserve a storage slot for constant variables, the optimiser will replace every occurrence
// of the constant variables in the compiling process. Hence it is okay to initialize these variables here, even
// this is an upgradable contract
uint256
public constant FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256
public constant ZERO_VALUE = 21663839004416932945382355908790599225266501822907911457504978515578255421292;
uint32 public constant ROOT_HISTORY_SIZE = 100;
uint32 public levels;
// the following variables are made public for easier testing and debugging and
// are not supposed to be accessed in regular code
bytes32[] public filledSubtrees;
bytes32[] public zeros;
uint32 public currentRootIndex;
uint32 public nextIndex;
bytes32[ROOT_HISTORY_SIZE] public roots;
// this tree stores two roots
bytes32 public rewardCurrentRoot;
uint32 public rewardCurrentBlocknum;
bytes32 public rewardNextRoot;
uint32 public rewardNextBlocknum;
// rewardRoot|--------blockcount-------|nextRewardRoot|----|
uint32 public blockCount;
event RewardUpdate(uint32 updateAtBlock, bytes32 newRewardRoot);
event BlockCountUpdate(uint32 blockCount);
// DO NOT implement a constructor because this is an upgradable logic.
// Use the initialize function as a constructor.
constructor() public {}
/**
* @dev The initializer
*/
function _initialize(uint32 _treeLevels, uint32 _blockCount)
internal
initializer
{
require(_treeLevels > 0, "_treeLevels should be greater than zero");
require(_treeLevels < 32, "_treeLevels should be less than 32");
levels = _treeLevels;
// new
blockCount = _blockCount;
bytes32 currentZero = bytes32(ZERO_VALUE);
zeros.push(currentZero);
filledSubtrees.push(currentZero);
for (uint32 i = 1; i < levels; i++) {
currentZero = hashLeftRight(currentZero, currentZero);
zeros.push(currentZero);
filledSubtrees.push(currentZero);
}
roots[0] = hashLeftRight(currentZero, currentZero);
//
rewardCurrentRoot = roots[0];
rewardCurrentBlocknum = uint32(block.number);
rewardNextRoot = roots[0];
rewardNextBlocknum = uint32(block.number);
}
function _setBlockCount(uint32 _blockCount) internal {
blockCount = _blockCount;
emit BlockCountUpdate(blockCount);
}
// poseidon
function hashLeftRight(bytes32 _left, bytes32 _right)
public
pure
returns (bytes32)
{
uint256[] memory inputs = new uint256[](2);
inputs[0] = uint256(_left);
inputs[1] = uint256(_right);
uint256 output = Hasher.poseidon(inputs);
return bytes32(output);
}
function _insert(bytes32 _leaf) internal returns (uint32 index) {
uint32 currentIndex = nextIndex;
require(
currentIndex != uint32(2)**levels,
"Merkle tree is full. No more leafs can be added"
);
nextIndex += 1;
bytes32 currentLevelHash = _leaf;
bytes32 left;
bytes32 right;
for (uint32 i = 0; i < levels; i++) {
if (currentIndex % 2 == 0) {
left = currentLevelHash;
right = zeros[i];
filledSubtrees[i] = currentLevelHash;
} else {
left = filledSubtrees[i];
right = currentLevelHash;
}
currentLevelHash = hashLeftRight(left, right);
currentIndex /= 2;
}
currentRootIndex = (currentRootIndex + 1) % ROOT_HISTORY_SIZE;
roots[currentRootIndex] = currentLevelHash;
// update roots
if ((uint32(block.number) - rewardNextBlocknum) >= blockCount) {
rewardCurrentRoot = rewardNextRoot;
rewardNextRoot = currentLevelHash;
// current tree root
rewardCurrentBlocknum = rewardNextBlocknum;
rewardNextBlocknum = uint32(block.number);
emit RewardUpdate(rewardCurrentBlocknum, rewardCurrentRoot);
}
return nextIndex - 1;
}
/**
@dev Whether the root is present in the root history
*/
function isKnownRoot(bytes32 _root) public view returns (bool) {
if (_root == 0) {
return false;
}
uint32 i = currentRootIndex;
do {
if (_root == roots[i]) {
return true;
}
if (i == 0) {
i = ROOT_HISTORY_SIZE;
}
i--;
} while (i != currentRootIndex);
return false;
}
//
function isRewardRoot(bytes32 _rroot) public view returns (bool) {
if (_rroot == 0) {
return false;
}
if (_rroot == rewardCurrentRoot) {
return true;
}
return false;
}
/**
@dev Returns the last root
*/
function getLastRoot() public view returns (bytes32) {
return roots[currentRootIndex];
}
}
/**
* @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;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @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 UpgradableReentrancyGuard {
// modified from _notEntered to _entered, to make lifer easier for upgrading contracts.
bool private _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(!_entered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_entered = true;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_entered = false;
}
}
interface WVerifier {
function verifyProof(bytes calldata _proof, uint256[7] calldata _input)
external
returns (bool);
}
interface RVerifier {
function verifyProof(bytes calldata _proof, uint256[6] calldata _input)
external
returns (bool);
}
contract BlenderCore is MerkleTreeWithHistory, UpgradableReentrancyGuard {
// Amount of deposit
uint256 public d_denomination;
// Amount of reward
uint256 public r_denomination;
// Withdraw nullifier list
mapping(bytes32 => bool) public nullifierHashes;
// Reward nullifier list
mapping(bytes32 => bool) public rewardNullifierHashes;
// Commitments
mapping(bytes32 => bool) public commitments;
// withdraw Verifier
WVerifier public withdrawVerifier;
// reward verifier
RVerifier public rewardVerifier;
// reward counter
uint32 public rewardCounter;
// operator can update snark verification key
// after the final trusted setup ceremony operator rights are supposed to be transferred to zero address
address public operator;
modifier onlyOperator {
require(
msg.sender == operator,
"Only operator can call this function."
);
_;
}
// relayer whitelisting
bool public relayerWhitelistingEnabled;
mapping(address => bool) public relayerWhitelist;
modifier onlyWhitelistedRelayer(address _relayer) {
if (relayerWhitelistingEnabled) {
require(relayerWhitelist[_relayer], "Not a whitelisted relayer");
}
_;
}
address public blnd;
uint256 public firstStageReward;
uint256 public secondStageReward;
uint256 public thirdStageReward;
uint256 public firstStageDepositors;
uint256 public secondStageDepositors;
event Deposit(
bytes32 indexed commitment,
uint32 leafIndex,
uint256 timestamp
);
event Reward(
address to,
bytes32 rewardNullifierHash,
address indexed relayer,
uint256 fee
);
event Withdrawal(
address to,
bytes32 withdrawNullifierHash,
bytes32 rewardNullifierHash,
address indexed relayer,
uint256 fee
);
event rewardUpdate(uint256 r_denomination, uint32 leafIndex);
event RelayerUpdate(address relayer, bool permitted);
// DO NOT implement a constructor because this is an upgradable logic.
// Use the initialize function as a constructor.
constructor() public {}
/**
* @dev The initializer
* @param _withdrawVerifier the address of SNARK verifier for this contract
* @param _rewardVerifier the address of SNARK verifier for this contract
* @param _d_denomination transfer amount for each deposit
* @param _merkleTreeHeight the height of deposits Merkle Tree
* @param _operator operator address (see operator comment above)
*/
function _initialize(
WVerifier _withdrawVerifier, // withdraw verifier
RVerifier _rewardVerifier, // reward verifier
uint256 _d_denomination,
uint32 _merkleTreeHeight,
uint32 _blockCount,
address _operator,
address _blnd,
uint256 _firstStageReward,
uint256 _secondStageReward,
uint256 _thirdStageReward,
uint256 _firstStageDepositors,
uint256 _secondStageDepositors
) internal initializer {
// call the initialize function of the parent contract (the constructor of the parent contract)
MerkleTreeWithHistory._initialize(_merkleTreeHeight, _blockCount);
// constructor logic
require(
_d_denomination > 0,
"Deposit denomination should be greater than 0"
);
firstStageReward = _firstStageReward;
secondStageReward = _secondStageReward;
thirdStageReward = _thirdStageReward;
firstStageDepositors = _firstStageDepositors;
secondStageDepositors = _secondStageDepositors;
withdrawVerifier = _withdrawVerifier;
rewardVerifier = _rewardVerifier;
operator = _operator;
d_denomination = _d_denomination;
r_denomination = firstStageReward;
blnd = _blnd;
}
// Should be unchanged
/**
@dev Deposit funds into the contract. The caller must send (for ETH) or approve (for ERC20) value equal to or `denomination` of this instance.
@param _commitment the note commitment, which is PedersenHash(nullifier + secret)
*/
function deposit(bytes32 _commitment) external payable nonReentrant {
require(!commitments[_commitment], "The commitment has been submitted");
uint32 insertedIndex = _insert(_commitment);
commitments[_commitment] = true;
_processDeposit();
emit Deposit(_commitment, insertedIndex, block.timestamp);
}
/** @dev this function is defined in a child contract */
function _processDeposit() internal;
/**
@dev Withdraw a deposit from the contract. `proof` is a zkSNARK proof data, and input is an array of circuit public inputs
`input` array consists of:
- merkle root of all deposits in the contract
- hash of unique deposit nullifier to prevent double spends
- the recipient of funds
- optional fee that goes to the transaction sender (usually a relay)
*/
function withdraw(
bytes calldata _proof,
bytes32 _root,
bytes32 _wdrHash,
bytes32 _rwdHash,
address payable _recipient,
address payable _relayer,
uint256 _fee,
uint256 _refund
) external payable nonReentrant onlyWhitelistedRelayer(_relayer) {
require(_fee <= d_denomination, "Fee exceeds transfer value");
require(
!nullifierHashes[_wdrHash],
"The withdraw note has been already spent for withdrawing"
);
require(
!nullifierHashes[_rwdHash],
"The reward note has been already spent for withdrawing"
);
require(isKnownRoot(_root), "Cannot find your merkle root");
// Make sure to use a recent one
require(
withdrawVerifier.verifyProof(
_proof,
[
uint256(_root),
uint256(_wdrHash),
uint256(_rwdHash),
uint256(_recipient),
uint256(_relayer),
_fee,
_refund
]
),
"Invalid withdraw proof"
);
nullifierHashes[_wdrHash] = true;
//
nullifierHashes[_rwdHash] = true;
//
rewardNullifierHashes[_rwdHash] = true;
// cannot obtain reward using this hash anymore
_processWithdraw(_recipient, _relayer, _fee, _refund);
emit Withdrawal(_recipient, _wdrHash, _rwdHash, _relayer, _fee);
}
function reward(
bytes calldata _rproof,
bytes32 _rroot,
bytes32 _rwdHash,
address payable _recipient,
address payable _relayer,
uint256 _fee,
uint256 _refund
) external payable nonReentrant onlyWhitelistedRelayer(_relayer) {
require(_fee <= r_denomination, "Fee exceeds transfer value");
require(
!rewardNullifierHashes[_rwdHash],
"The reward note has been already redeemed"
);
require(isRewardRoot(_rroot), "Cannot find your merkle root");
// Make sure to use a recent one
require(
rewardVerifier.verifyProof(
_rproof,
[
uint256(_rroot),
uint256(_rwdHash),
uint256(_recipient),
uint256(_relayer),
_fee,
_refund
]
),
"Invalid reward proof"
);
// update reward at certain checkpoints
if (rewardCounter == firstStageDepositors) {
r_denomination = secondStageReward;
emit rewardUpdate(r_denomination, rewardCounter);
}
if (rewardCounter == secondStageDepositors) {
r_denomination = thirdStageReward;
emit rewardUpdate(r_denomination, rewardCounter);
}
// cannot obtain reward using this hash anymore
rewardNullifierHashes[_rwdHash] = true;
_processReward(_recipient, _relayer, _fee, _refund);
rewardCounter = rewardCounter + 1;
emit Reward(_recipient, _rwdHash, _relayer, _fee);
}
/** @dev this function is defined in a child contract */
function _processWithdraw(
address payable _recipient,
address payable _relayer,
uint256 _fee,
uint256 _refund
) internal;
function _processReward(
address payable _recipient,
address payable _relayer,
uint256 _fee,
uint256 _refund
) internal {
require(
msg.value == _refund,
"Incorrect refund amount received by the contract"
);
SafeERC20.safeTransfer(IERC20(blnd), _recipient, r_denomination - _fee);
if (_fee > 0) {
SafeERC20.safeTransfer(IERC20(blnd), _relayer, _fee);
}
// to prevent attacker from burning relayer eth in fee
if (_refund > 0) {
(bool success, ) = _recipient.call.value(_refund)("");
if (!success) {
_relayer.transfer(_refund);
}
}
}
/** @dev whether a note is already spent */
// TODO blnd may need to verify two nullifier hashes is needed
function isSpent(bytes32 _wdrHash) public view returns (bool) {
return nullifierHashes[_wdrHash];
}
function isRedeem(bytes32 _rwdHash) public view returns (bool) {
return rewardNullifierHashes[_rwdHash];
}
/** @dev whether an array of notes is already spent */
function isSpentArray(bytes32[] calldata _nullifierHashes)
external
view
returns (bool[] memory spent)
{
spent = new bool[](_nullifierHashes.length);
for (uint256 i = 0; i < _nullifierHashes.length; i++) {
if (isSpent(_nullifierHashes[i])) {
spent[i] = true;
}
}
}
/** @dev whether an array of notes is already spent */
function isRedeemArray(bytes32[] calldata _nullifierHashes)
external
view
returns (bool[] memory redeem)
{
redeem = new bool[](_nullifierHashes.length);
for (uint256 i = 0; i < _nullifierHashes.length; i++) {
if (isRedeem(_nullifierHashes[i])) {
redeem[i] = true;
}
}
}
/**
@dev allow operator to update SNARK verification keys. This is needed to update keys after the final trusted setup ceremony is held.
After that operator rights are supposed to be transferred to zero address
*/
// update withdraw verifier
function updateWithdrawVerifier(address _newVerifier)
external
onlyOperator
{
withdrawVerifier = WVerifier(_newVerifier);
}
// update reward verifier
function updateRewardVerifier(address _newVerifier) external onlyOperator {
rewardVerifier = RVerifier(_newVerifier);
}
/** @dev operator can change his address */
function changeOperator(address _newOperator) external onlyOperator {
operator = _newOperator;
}
/**
* @dev operator can enable relayer whitelisting
*/
function enableRelayerWhitelisting() external onlyOperator nonReentrant {
relayerWhitelistingEnabled = true;
}
/**
* @dev operator can disable relayer whitelisting
*/
function disableRelayerWhitelisting() external onlyOperator nonReentrant {
relayerWhitelistingEnabled = false;
}
/**
* @dev operator can add a relayer to the whitelist.
*/
function addRelayer(address _relayer) external onlyOperator nonReentrant {
relayerWhitelist[_relayer] = true;
emit RelayerUpdate(_relayer, relayerWhitelist[_relayer]);
}
/**
* @dev operator can remove a relayer from the whitelist.
*/
function removeRelayer(address _relayer)
external
onlyOperator
nonReentrant
{
relayerWhitelist[_relayer] = false;
emit RelayerUpdate(_relayer, relayerWhitelist[_relayer]);
}
/**
* @dev operator can change the number of blocks between the current and next reward roots
*/
function setBlockCount(uint32 _blockCount)
external
onlyOperator
nonReentrant
{
_setBlockCount(_blockCount);
}
}
interface AToken {
function balanceOf(address _user) external view returns (uint256);
function redeem(uint256 _amount) external;
}
interface ALendingPool {
function deposit(
address _reserve,
uint256 _amount,
uint16 _referralCode
) external payable;
}
interface ALendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
}
contract AETHBlender is Initializable, BlenderCore {
ALendingPoolAddressesProvider public lendingPoolAddressesProvider;
AToken public aToken;
address public reserve;
uint256 public depositors;
// DO NOT implement a constructor because this is an upgradable logic.
// Use the initialize function as a constructor.
constructor() public {}
function initialize(
WVerifier _withdrawVerifier,
RVerifier _rewardVerifier,
uint256 _d_denomination,
uint32 _merkleTreeHeight,
uint32 _blockCount,
address _operator,
address _blnd,
address _aToken,
address _reserve,
uint256 _firstStageReward,
uint256 _secondStageReward,
uint256 _thirdStageReward,
uint256 _firstStageDepositors,
uint256 _secondStageDepositors
) public {
// call the initialize function of the parent contract (the constructor of the parent contract)
BlenderCore._initialize(
_withdrawVerifier,
_rewardVerifier,
_d_denomination,
_merkleTreeHeight,
_blockCount,
_operator,
_blnd,
_firstStageReward,
_secondStageReward,
_thirdStageReward,
_firstStageDepositors,
_secondStageDepositors
);
// constructor logic
lendingPoolAddressesProvider = ALendingPoolAddressesProvider(
0x24a42fD28C976A61Df5D00D0599C34c4f90748c8
);
aToken = AToken(_aToken);
reserve = _reserve;
}
function _processDeposit() internal {
require(
msg.value == d_denomination,
"Please send `mixDenomination` ETH along with transaction"
);
// Deposit all the balance
uint256 balance = address(this).balance;
ALendingPool(lendingPoolAddressesProvider.getLendingPool())
.deposit
.value(balance)(reserve, balance, 0);
depositors++;
}
function _processWithdraw(
address payable _recipient,
address payable _relayer,
uint256 _fee,
uint256 _refund
) internal {
require(
msg.value == 0,
"Message value is supposed to be zero for ETH instance"
);
require(
_refund == 0,
"Refund value is supposed to be zero for ETH instance"
);
require(depositors > 0, "Number of depositors must be positive");
uint256 beforeBalance = address(this).balance;
uint256 aBalance = aToken.balanceOf(address(this));
uint256 redeemAmount = SafeMath.div(aBalance, depositors);
aToken.redeem(redeemAmount);
uint256 afterBalance = address(this).balance;
uint256 redeemedAmount = SafeMath.sub(afterBalance, beforeBalance);
(bool success, ) = _recipient.call.value(redeemedAmount - _fee)("");
require(success, "payment to _recipient did not go thru");
if (_fee > 0) {
(success, ) = _relayer.call.value(_fee)("");
require(success, "payment to _relayer did not go thru");
}
depositors--;
}
function() external payable {}
} | * @dev operator can disable relayer whitelisting/ | function disableRelayerWhitelisting() external onlyOperator nonReentrant {
relayerWhitelistingEnabled = false;
}
| 6,782,026 | [
1,
9497,
848,
4056,
1279,
1773,
10734,
310,
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
] | [
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,
445,
4056,
1971,
1773,
18927,
310,
1435,
3903,
1338,
5592,
1661,
426,
8230,
970,
288,
203,
3639,
1279,
1773,
18927,
310,
1526,
273,
629,
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
] |
// Sources flattened with hardhat v2.8.3 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// 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/token/ERC20/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 {}
}
// File @openzeppelin/contracts/utils/math/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @uniswap/v2-core/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
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;
}
// File @uniswap/v2-core/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
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;
}
// File @uniswap/v2-periphery/contracts/interfaces/[email protected]
pragma solidity >=0.6.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);
}
// File @uniswap/v2-periphery/contracts/interfaces/[email protected]
pragma solidity >=0.6.2;
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;
}
// File contracts/BLUME.sol
pragma solidity ^0.8.0;
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
library SafeMathInt {
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
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();
}
}
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns (uint256);
/// @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 DividendsDistributed(address indexed from, uint256 weiAmount);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(address indexed to, uint256 weiAmount);
}
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner)
external
view
returns (uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner)
external
view
returns (uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner)
external
view
returns (uint256);
}
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract DividendPayingToken is Context, ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends 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 magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` 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 distributeDividends() public payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(_msgSender(), msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
(bool success,) = user.call{value: _withdrawableDividend, gas: 3000}("");
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return (magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() + magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends 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);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] - (magnifiedDividendPerShare.mul(value)).toInt256Safe();
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends 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);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] + (magnifiedDividendPerShare.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 ERC20DividendToken is Context, ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private swapping;
TokenDividendTracker public dividendTracker;
uint256 public minTokensBeforeSwap;
mapping(address => bool) public isBlacklisted;
uint256 public rewardsFee;
uint256 public liquidityFee;
uint256 public treasuryFee;
uint256 public totalFees;
address public treasuryAddress;
bool public tradingEnabled;
// exlcude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
// 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;
uint256 public maxTxAmount;
uint256 public maxWalletAmount;
mapping (address => bool) public isExcludedFromLimits;
event DeployedDividendTracker(
address indexed newAddress
);
event UpdateUniswapV2Router(
address indexed newAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SendDividends(uint256 tokensSwapped, uint256 amount);
event SendDividendsToTreasury(uint256 tokensSwapped, uint256 amount);
constructor(string memory name_, string memory symbol_, uint256 totalSupply_, address routerV2_, address treasuryAddress_) ERC20(name_, symbol_) {
rewardsFee = 3;
liquidityFee = 2;
treasuryFee = 10;
totalFees = rewardsFee.add(liquidityFee).add(treasuryFee);
require(totalFees <= 100, "Total fee is over 100%");
treasuryAddress = treasuryAddress_;
minTokensBeforeSwap = 1_000 * (10**18);
maxTxAmount = totalSupply_ * 3 * (10**16); // 3%
maxWalletAmount = totalSupply_ * (10**17); // 10%
deployDividendTracker(routerV2_);
_updateUniswapV2Router(routerV2_);
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(treasuryAddress, true);
excludeFromLimits(owner(), true);
excludeFromLimits(address(this), true);
excludeFromLimits(treasuryAddress, true);
excludeFromLimits(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), totalSupply_ * (10**18));
}
receive() external payable {}
function excludeFromLimits(address account, bool excluded) public onlyOwner {
isExcludedFromLimits[account] = excluded;
}
function changeMaxTxAmount(uint256 amount) public onlyOwner {
maxTxAmount = amount;
}
function changeMaxWalletAmount(uint256 amount) public onlyOwner {
maxWalletAmount = amount;
}
function setMinTokensBeforeSwap(uint256 amount) external onlyOwner {
minTokensBeforeSwap = amount;
}
function enableTrading(bool enabled) external onlyOwner {
tradingEnabled = enabled;
}
function deployDividendTracker(address _uniswapV2Router) internal {
dividendTracker = new TokenDividendTracker();
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(0xdead));
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
emit DeployedDividendTracker(address(dividendTracker));
}
function _updateUniswapV2Router(address newAddress) internal {
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
excludeFromLimits(newAddress, true);
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
emit UpdateUniswapV2Router(newAddress);
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(
address[] calldata accounts,
bool excluded
) public onlyOwner {
for (uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setTreasuryWallet(address wallet) external onlyOwner {
treasuryAddress = wallet;
}
function setRewardsFee(uint256 value) external onlyOwner {
rewardsFee = value;
totalFees = rewardsFee.add(liquidityFee).add(treasuryFee);
}
function setLiquidityFee(uint256 value) external onlyOwner {
liquidityFee = value;
totalFees = rewardsFee.add(liquidityFee).add(treasuryFee);
}
function setTreasuryFee(uint256 value) external onlyOwner {
treasuryFee = value;
totalFees = rewardsFee.add(liquidityFee).add(treasuryFee);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"ERC20DividendToken: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function blacklistAddress(address account, bool value) external onlyOwner {
isBlacklisted[account] = value;
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(
automatedMarketMakerPairs[pair] != value,
"ERC20DividendToken: Automated market maker pair is already set to that value"
);
automatedMarketMakerPairs[pair] = value;
if (value) {
excludeFromLimits(pair, true);
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account)
public
view
returns (uint256)
{
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account)
public
view
returns (uint256)
{
return dividendTracker.balanceOf(account);
}
function excludeFromDividends(address account) external onlyOwner {
dividendTracker.excludeFromDividends(account);
}
function includeInDividends(address account) external onlyOwner {
dividendTracker.includeInDividends(account, balanceOf(account));
}
function getAccountDividendsInfo(address account)
external
view
returns (
address,
int256,
uint256,
uint256
)
{
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external
view
returns (
address,
int256,
uint256,
uint256
)
{
return dividendTracker.getAccountAtIndex(index);
}
function claim() external {
dividendTracker.processAccount(_msgSender());
}
function getNumberOfDividendTokenHolders() external view returns (uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
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");
require(balanceOf(from) >= amount, "ERC20: transfer amount exceeds balance");
require(!isBlacklisted[from] && !isBlacklisted[to], "Blacklisted address");
if ((automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]) && (from != owner() && to != owner())) {
require(tradingEnabled, "Trading is not enabled");
}
if (!isExcludedFromLimits[from] || (automatedMarketMakerPairs[from] && !isExcludedFromLimits[to])) {
require(amount <= maxTxAmount, "Anti-whale: Transfer amount exceeds max limit");
}
if (!isExcludedFromLimits[to]) {
require(balanceOf(to) + amount <= maxWalletAmount, "Anti-whale: Wallet amount exceeds max limit");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minTokensBeforeSwap;
if (
canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
if (treasuryFee > 0) {
uint256 treasuryTokens = contractTokenBalance.mul(treasuryFee).div(totalFees);
swapAndSendDividendsToTreasury(treasuryTokens);
}
if (liquidityFee > 0) {
uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees);
swapAndLiquify(swapTokens);
}
if (rewardsFee > 0) {
uint256 rewardTokens = balanceOf(address(this));
swapAndSendDividends(rewardTokens);
}
swapping = false;
}
bool takeFee = !swapping && (automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]);
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(totalFees).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(from, balanceOf(from)) {} catch {}
try dividendTracker.setBalance(to, balanceOf(to)) {} catch {}
}
function swapAndLiquify(uint256 tokens) private {
// split the contract balance into halves
uint256 half = tokens.div(2);
uint256 otherHalf = tokens.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
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
address(0xdead),
block.timestamp
);
}
function swapAndSendDividends(uint256 tokens) private {
swapTokensForEth(tokens);
uint256 dividends = address(this).balance;
(bool success,) = payable(address(dividendTracker)).call{value: dividends}("");
if(success) {
emit SendDividends(tokens, dividends);
}
}
function swapAndSendDividendsToTreasury(uint256 tokens) private {
uint256 initialBalance = address(this).balance;
swapTokensForEth(tokens);
uint256 dividends = address(this).balance.sub(initialBalance);
(bool success,) = payable(treasuryAddress).call{value: dividends}("");
if(success) {
emit SendDividendsToTreasury(tokens, dividends);
}
}
}
contract TokenDividendTracker is Ownable, DividendPayingToken {
using SafeMath for uint256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
mapping(address => bool) public isExcludedFromDividends;
uint256 public minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event IncludeInDividends(address indexed account);
event Claim(
address indexed account,
uint256 amount
);
constructor() DividendPayingToken("Dividend_Tracker", "Dividend_Tracker") {
minimumTokenBalanceForDividends = 1 * (10**18);
}
function excludeFromDividends(address account) external onlyOwner {
require(!isExcludedFromDividends[account]);
isExcludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromDividends(account);
}
function includeInDividends(address account, uint256 balance) external onlyOwner {
require(isExcludedFromDividends[account]);
isExcludedFromDividends[account] = false;
_setBalance(account, balance);
tokenHoldersMap.set(account, balance);
emit IncludeInDividends(account);
}
function getNumberOfTokenHolders() external view returns (uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public
view
returns (
address account,
int256 index,
uint256 withdrawableDividends,
uint256 totalDividends
)
{
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
}
function getAccountAtIndex(uint256 index)
public
view
returns (
address,
int256,
uint256,
uint256
)
{
if (index >= tokenHoldersMap.size()) {
return (address(0), -1, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function setBalance(address account, uint256 newBalance)
external
onlyOwner
{
if (isExcludedFromDividends[account]) {
return;
}
if (newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
} else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
}
function processAccount(address account)
public
onlyOwner
returns (bool)
{
uint256 amount = _withdrawDividendOfUser(payable(account));
if (amount > 0) {
emit Claim(account, amount);
return true;
}
return false;
}
}
contract BLUME is ERC20DividendToken {
uint256 private _tokenSupply = 10_000_000;
/**
* @dev Choose proper router address according to your network:
* Ethereum mainnet: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D (Uniswap)
* BSC mainnet: 0x10ED43C718714eb63d5aA57B78B54704E256024E (PancakeSwap)
* BSC testnet: 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3
*/
address private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor (address _treasuryAddress) ERC20DividendToken("Blume Capital", "BLUME", _tokenSupply, _routerAddress, _treasuryAddress) {
// Fees to be set in parent constructor
}
} | if any account belongs to _isExcludedFromFee account then remove the fee | 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");
require(balanceOf(from) >= amount, "ERC20: transfer amount exceeds balance");
require(!isBlacklisted[from] && !isBlacklisted[to], "Blacklisted address");
if ((automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]) && (from != owner() && to != owner())) {
require(tradingEnabled, "Trading is not enabled");
}
if (!isExcludedFromLimits[from] || (automatedMarketMakerPairs[from] && !isExcludedFromLimits[to])) {
require(amount <= maxTxAmount, "Anti-whale: Transfer amount exceeds max limit");
}
if (!isExcludedFromLimits[to]) {
require(balanceOf(to) + amount <= maxWalletAmount, "Anti-whale: Wallet amount exceeds max limit");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= minTokensBeforeSwap;
if (
canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
if (treasuryFee > 0) {
uint256 treasuryTokens = contractTokenBalance.mul(treasuryFee).div(totalFees);
swapAndSendDividendsToTreasury(treasuryTokens);
}
if (liquidityFee > 0) {
uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees);
swapAndLiquify(swapTokens);
}
if (rewardsFee > 0) {
uint256 rewardTokens = balanceOf(address(this));
swapAndSendDividends(rewardTokens);
}
swapping = false;
}
bool takeFee = !swapping && (automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]);
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(totalFees).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
}
| 437,324 | [
1,
430,
1281,
2236,
11081,
358,
389,
291,
16461,
1265,
14667,
2236,
1508,
1206,
326,
14036,
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,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
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,
12296,
951,
12,
2080,
13,
1545,
3844,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
203,
3639,
2583,
12,
5,
291,
13155,
18647,
63,
2080,
65,
597,
401,
291,
13155,
18647,
63,
869,
6487,
315,
13155,
18647,
1758,
8863,
203,
203,
3639,
309,
14015,
5854,
362,
690,
3882,
278,
12373,
10409,
63,
2080,
65,
747,
18472,
690,
3882,
278,
12373,
10409,
63,
869,
5717,
597,
261,
2080,
480,
3410,
1435,
597,
358,
480,
3410,
1435,
3719,
288,
203,
5411,
2583,
12,
313,
14968,
1526,
16,
315,
1609,
7459,
353,
486,
3696,
8863,
203,
3639,
289,
203,
203,
3639,
309,
16051,
291,
16461,
1265,
12768,
63,
2080,
65,
747,
261,
5854,
362,
690,
3882,
278,
12373,
10409,
63,
2080,
65,
597,
401,
291,
16461,
1265,
12768,
63,
869,
22643,
288,
203,
5411,
2583,
12,
8949,
1648,
943,
4188,
6275,
16,
315,
14925,
77,
17,
3350,
5349,
30,
12279,
3844,
14399,
943,
1800,
8863,
203,
3639,
289,
203,
3639,
309,
16051,
291,
16461,
1265,
12768,
63,
869,
5717,
288,
203,
5411,
2583,
12,
12296,
951,
12,
869,
13,
397,
3844,
2
] |
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
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);
}
/**
* @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.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to 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 Scale Token Contract
* @file Scale.sol
* @author Jared Downing and Kane Thomas of the Scale Network
* @version 1.0
*
* @section DESCRIPTION
*
* This is an ERC20-based token with staking and inflationary functionality.
*
*************************************************************/
//////////////////////////////////
/// OpenZeppelin library imports
//////////////////////////////////
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
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);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title 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);
emit 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;
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];
}
/**
* @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);
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, 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;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
* Modified to allow minting for non-owner addresses
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
/**
* @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) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
}
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
assert(owner.send(address(this).balance));
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
//////////////////////////////////
/// Scale Token
//////////////////////////////////
contract Scale is MintableToken, HasNoEther, BurnableToken {
// Libraries
using SafeMath for uint;
//////////////////////
// Token Information
//////////////////////
string public constant name = "SCALE";
string public constant symbol = "SCALE";
uint8 public constant decimals = 18;
///////////////////////////////////////////////////////////
// Variables For Staking and Pooling
///////////////////////////////////////////////////////////
// -- Pool Minting Rates and Percentages -- //
// Pool for Scale distribution to rewards pool
// Set to 0 to prohibit issuing to the pool before it is assigned
address public pool = address(0);
// Pool and Owner minted tokens per second
uint public poolMintRate;
uint public ownerMintRate;
// Amount of Scale to be staked to the pool, staking, and owner, as calculated through their percentages
uint public poolMintAmount;
uint public stakingMintAmount;
uint public ownerMintAmount;
// Scale distribution percentages
uint public poolPercentage = 70;
uint public ownerPercentage = 5;
uint public stakingPercentage = 25;
// Last time minted for owner and pool
uint public ownerTimeLastMinted;
uint public poolTimeLastMinted;
// -- Staking -- //
// Minted tokens per second
uint public stakingMintRate;
// Total Scale currently staked
uint public totalScaleStaked;
// Mapping of the timestamp => totalStaking that is created each time an address stakes or unstakes
mapping (uint => uint) totalStakingHistory;
// Variable for staking accuracy. Set to 86400 for seconds in a day so that staking gains are based on the day an account begins staking.
uint timingVariable = 86400;
// Address staking information
struct AddressStakeData {
uint stakeBalance;
uint initialStakeTime;
uint unstakeTime;
mapping (uint => uint) stakePerDay;
}
// Track all tokens staked
mapping (address => AddressStakeData) public stakeBalances;
// -- Inflation -- //
// Inflation rate begins at 100% per year and decreases by 30% per year until it reaches 10% where it decreases by 0.5% per year
uint256 inflationRate = 1000;
// Used to manage when to inflate. Allowed to inflate once per year until the rate reaches 1%.
uint256 public lastInflationUpdate;
// -- Events -- //
// Fired when tokens are staked
event Stake(address indexed staker, uint256 value);
// Fired when tokens are unstaked
event Unstake(address indexed unstaker, uint256 stakedAmount);
// Fired when a user claims their stake
event ClaimStake(address indexed claimer, uint256 stakedAmount, uint256 stakingGains);
//////////////////////////////////////////////////
/// Scale Token Functionality
//////////////////////////////////////////////////
/// @dev Scale token constructor
constructor() public {
// Assign owner
owner = msg.sender;
// Assign initial owner supply
uint _initOwnerSupply = 10000000 ether;
// Mint given to owner only one-time
bool _success = mint(msg.sender, _initOwnerSupply);
// Require minting success
require(_success);
// Set pool and owner last minted to ensure extra coins are not minted by either
ownerTimeLastMinted = now;
poolTimeLastMinted = now;
// Set minting amount for pool, staking, and owner over the course of 1 year
poolMintAmount = _initOwnerSupply.mul(poolPercentage).div(100);
ownerMintAmount = _initOwnerSupply.mul(ownerPercentage).div(100);
stakingMintAmount = _initOwnerSupply.mul(stakingPercentage).div(100);
// One year in seconds
uint _oneYearInSeconds = 31536000 ether;
// Set the rate of coins minted per second for the pool, owner, and global staking
poolMintRate = calculateFraction(poolMintAmount, _oneYearInSeconds, decimals);
ownerMintRate = calculateFraction(ownerMintAmount, _oneYearInSeconds, decimals);
stakingMintRate = calculateFraction(stakingMintAmount, _oneYearInSeconds, decimals);
// Set the last time inflation was updated to now so that the next time it can be updated is 1 year from now
lastInflationUpdate = now;
}
/////////////
// Inflation
/////////////
/// @dev the inflation rate begins at 100% and decreases by 30% every year until it reaches 10%
/// at 10% the rate begins to decrease by 0.5% until it reaches 1%
function adjustInflationRate() private {
// Make sure adjustInflationRate cannot be called for at least another year
lastInflationUpdate = now;
// Decrease inflation rate by 30% each year
if (inflationRate > 100) {
inflationRate = inflationRate.sub(300);
}
// Inflation rate reaches 10%. Decrease inflation rate by 0.5% from here on out until it reaches 1%.
else if (inflationRate > 10) {
inflationRate = inflationRate.sub(5);
}
adjustMintRates();
}
/// @dev adjusts the mint rate when the yearly inflation update is called
function adjustMintRates() internal {
// Calculate new mint amount of Scale that should be created per year.
poolMintAmount = totalSupply.mul(inflationRate).div(1000).mul(poolPercentage).div(100);
ownerMintAmount = totalSupply.mul(inflationRate).div(1000).mul(ownerPercentage).div(100);
stakingMintAmount = totalSupply.mul(inflationRate).div(1000).mul(stakingPercentage).div(100);
// Adjust Scale created per-second for each rate
poolMintRate = calculateFraction(poolMintAmount, 31536000 ether, decimals);
ownerMintRate = calculateFraction(ownerMintAmount, 31536000 ether, decimals);
stakingMintRate = calculateFraction(stakingMintAmount, 31536000 ether, decimals);
}
/// @dev anyone can call this function to update the inflation rate yearly
function updateInflationRate() public {
// Require 1 year to have passed for every inflation adjustment
require(now.sub(lastInflationUpdate) >= 31536000);
adjustInflationRate();
}
/////////////
// Staking
/////////////
/// @dev staking function which allows users to stake an amount of tokens to gain interest for up to 1 year
function stake(uint _stakeAmount) external {
// Require that tokens are staked successfully
require(stakeScale(msg.sender, _stakeAmount));
}
/// @dev staking function which allows users to stake an amount of tokens for another user
function stakeFor(address _user, uint _amount) external {
// Stake for the user
require(stakeScale(_user, _amount));
}
/// @dev Transfer tokens from the contract to the user when unstaking
/// @param _value uint256 the amount of tokens to be transferred
function transferFromContract(uint _value) internal {
// Sanity check to make sure we are not transferring more than the contract has
require(_value <= balances[address(this)]);
// Add to the msg.sender balance
balances[msg.sender] = balances[msg.sender].add(_value);
// Subtract from the contract's balance
balances[address(this)] = balances[address(this)].sub(_value);
// Fire an event for transfer
emit Transfer(address(this), msg.sender, _value);
}
/// @dev stake function reduces the user's total available balance and adds it to their staking balance
/// @param _value how many tokens a user wants to stake
function stakeScale(address _user, uint256 _value) private returns (bool success) {
// You can only stake / stakeFor as many tokens as you have
require(_value <= balances[msg.sender]);
// Require the user is not in power down period
require(stakeBalances[_user].unstakeTime == 0);
// Transfer tokens to contract address
transfer(address(this), _value);
// Now as a day
uint _nowAsDay = now.div(timingVariable);
// Adjust the new staking balance
uint _newStakeBalance = stakeBalances[_user].stakeBalance.add(_value);
// If this is the initial stake time, save
if (stakeBalances[_user].stakeBalance == 0) {
// Save the time that the stake started
stakeBalances[_user].initialStakeTime = _nowAsDay;
}
// Add stake amount to staked balance
stakeBalances[_user].stakeBalance = _newStakeBalance;
// Assign the total amount staked at this day
stakeBalances[_user].stakePerDay[_nowAsDay] = _newStakeBalance;
// Increment the total staked tokens
totalScaleStaked = totalScaleStaked.add(_value);
// Set the new staking history
setTotalStakingHistory();
// Fire an event for newly staked tokens
emit Stake(_user, _value);
return true;
}
/// @dev deposit a user's initial stake plus earnings if the user unstaked at least 14 days ago
function claimStake() external returns (bool) {
// Require that at least 14 days have passed (days)
require(now.div(timingVariable).sub(stakeBalances[msg.sender].unstakeTime) >= 14);
// Get the user's stake balance
uint _userStakeBalance = stakeBalances[msg.sender].stakeBalance;
// Calculate tokens to mint using unstakeTime, rewards are not received during power-down period
uint _tokensToMint = calculateStakeGains(stakeBalances[msg.sender].unstakeTime);
// Clear out stored data from mapping
stakeBalances[msg.sender].stakeBalance = 0;
stakeBalances[msg.sender].initialStakeTime = 0;
stakeBalances[msg.sender].unstakeTime = 0;
// Return the stake balance to the staker
transferFromContract(_userStakeBalance);
// Mint the new tokens to the sender
mint(msg.sender, _tokensToMint);
// Scale unstaked event
emit ClaimStake(msg.sender, _userStakeBalance, _tokensToMint);
return true;
}
/// @dev allows users to start the reclaim process for staked tokens and stake rewards
/// @return bool on success
function initUnstake() external returns (bool) {
// Require that the user has not already started the unstaked process
require(stakeBalances[msg.sender].unstakeTime == 0);
// Require that there was some amount staked
require(stakeBalances[msg.sender].stakeBalance > 0);
// Log time that user started unstaking
stakeBalances[msg.sender].unstakeTime = now.div(timingVariable);
// Subtract stake balance from totalScaleStaked
totalScaleStaked = totalScaleStaked.sub(stakeBalances[msg.sender].stakeBalance);
// Set this every time someone adjusts the totalScaleStaked amount
setTotalStakingHistory();
// Scale unstaked event
emit Unstake(msg.sender, stakeBalances[msg.sender].stakeBalance);
return true;
}
/// @dev function to let the user know how much time they have until they can claim their tokens from unstaking
/// @param _user to check the time until claimable of
/// @return uint time in seconds until they may claim
function timeUntilClaimAvaliable(address _user) view external returns (uint) {
return stakeBalances[_user].unstakeTime.add(14).mul(86400);
}
/// @dev function to check the staking balance of a user
/// @param _user to check the balance of
/// @return uint of the stake balance
function stakeBalanceOf(address _user) view external returns (uint) {
return stakeBalances[_user].stakeBalance;
}
/// @dev returns how much Scale a user has earned so far
/// @param _now is passed in to allow for a gas-free analysis
/// @return staking gains based on the amount of time passed since staking began
function getStakingGains(uint _now) view public returns (uint) {
if (stakeBalances[msg.sender].stakeBalance == 0) {
return 0;
}
return calculateStakeGains(_now.div(timingVariable));
}
/// @dev Calculates staking gains
/// @param _unstakeTime when the user stopped staking.
/// @return uint for total coins to be minted
function calculateStakeGains(uint _unstakeTime) view private returns (uint mintTotal) {
uint _initialStakeTimeInVariable = stakeBalances[msg.sender].initialStakeTime; // When the user started staking as a unique day in unix time
uint _timePassedSinceStakeInVariable = _unstakeTime.sub(_initialStakeTimeInVariable); // How much time has passed, in days, since the user started staking.
uint _stakePercentages = 0; // Keeps an additive track of the user's staking percentages over time
uint _tokensToMint = 0; // How many new Scale tokens to create
uint _lastDayStakeWasUpdated; // Last day the totalScaleStaked was updated
uint _lastStakeDay; // Last day that the user staked
// If user staked and init unstaked on the same day, gains are 0
if (_timePassedSinceStakeInVariable == 0) {
return 0;
}
// If user has been staking longer than 365 days, staked days after 365 days do not earn interest
else if (_timePassedSinceStakeInVariable >= 365) {
_unstakeTime = _initialStakeTimeInVariable.add(365);
_timePassedSinceStakeInVariable = 365;
}
// Average this msg.sender's relative percentage ownership of totalScaleStaked throughout each day since they started staking
for (uint i = _initialStakeTimeInVariable; i < _unstakeTime; i++) {
// Total amount user has staked on i day
uint _stakeForDay = stakeBalances[msg.sender].stakePerDay[i];
// If this was a day that the user staked or added stake
if (_stakeForDay != 0) {
// If the day exists add it to the percentages
if (totalStakingHistory[i] != 0) {
// If the day does exist add it to the number to be later averaged as a total average percentage of total staking
_stakePercentages = _stakePercentages.add(calculateFraction(_stakeForDay, totalStakingHistory[i], decimals));
// Set the last day someone staked
_lastDayStakeWasUpdated = totalStakingHistory[i];
}
else {
// Use the last day found in the totalStakingHistory mapping
_stakePercentages = _stakePercentages.add(calculateFraction(_stakeForDay, _lastDayStakeWasUpdated, decimals));
}
_lastStakeDay = _stakeForDay;
}
else {
// If the day exists add it to the percentages
if (totalStakingHistory[i] != 0) {
// If the day does exist add it to the number to be later averaged as a total average percentage of total staking
_stakePercentages = _stakePercentages.add(calculateFraction(_lastStakeDay, totalStakingHistory[i], decimals));
// Set the last day someone staked
_lastDayStakeWasUpdated = totalStakingHistory[i];
}
else {
// Use the last day found in the totalStakingHistory mapping
_stakePercentages = _stakePercentages.add(calculateFraction(_lastStakeDay, _lastDayStakeWasUpdated, decimals));
}
}
}
// Get the account's average percentage staked of the total stake over the course of all days they have been staking
uint _stakePercentageAverage = calculateFraction(_stakePercentages, _timePassedSinceStakeInVariable, 0);
// Calculate this account's mint rate per second while staking
uint _finalMintRate = stakingMintRate.mul(_stakePercentageAverage);
// Account for 18 decimals when calculating the amount of tokens to mint
_finalMintRate = _finalMintRate.div(1 ether);
// Calculate total tokens to be minted. Multiply by timingVariable to convert back to seconds.
_tokensToMint = calculateMintTotal(_timePassedSinceStakeInVariable.mul(timingVariable), _finalMintRate);
return _tokensToMint;
}
/// @dev set the new totalStakingHistory mapping to the current timestamp and totalScaleStaked
function setTotalStakingHistory() private {
// Get now in terms of the variable staking accuracy (days in Scale's case)
uint _nowAsTimingVariable = now.div(timingVariable);
// Set the totalStakingHistory as a timestamp of the totalScaleStaked today
totalStakingHistory[_nowAsTimingVariable] = totalScaleStaked;
}
/////////////
// Scale Owner Claiming
/////////////
/// @dev allows contract owner to claim their allocated mint
function ownerClaim() external onlyOwner {
require(now > ownerTimeLastMinted);
uint _timePassedSinceLastMint; // The amount of time passed since the owner claimed in seconds
uint _tokenMintCount; // The amount of new tokens to mint
bool _mintingSuccess; // The success of minting the new Scale tokens
// Calculate the number of seconds that have passed since the owner last took a claim
_timePassedSinceLastMint = now.sub(ownerTimeLastMinted);
assert(_timePassedSinceLastMint > 0);
// Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate
_tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, ownerMintRate);
// Mint the owner's tokens; this also increases totalSupply
_mintingSuccess = mint(msg.sender, _tokenMintCount);
require(_mintingSuccess);
// New minting was a success. Set last time minted to current block.timestamp (now)
ownerTimeLastMinted = now;
}
////////////////////////////////
// Scale Pool Distribution
////////////////////////////////
// @dev anyone can call this function that mints Scale to the pool dedicated to Scale distribution to rewards pool
function poolIssue() public {
// Do not allow tokens to be minted to the pool until the pool is set
require(pool != address(0));
// Make sure time has passed since last minted to pool
require(now > poolTimeLastMinted);
require(pool != address(0));
uint _timePassedSinceLastMint; // The amount of time passed since the pool claimed in seconds
uint _tokenMintCount; // The amount of new tokens to mint
bool _mintingSuccess; // The success of minting the new Scale tokens
// Calculate the number of seconds that have passed since the owner last took a claim
_timePassedSinceLastMint = now.sub(poolTimeLastMinted);
assert(_timePassedSinceLastMint > 0);
// Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate
_tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, poolMintRate);
// Mint the owner's tokens; this also increases totalSupply
_mintingSuccess = mint(pool, _tokenMintCount);
require(_mintingSuccess);
// New minting was a success! Set last time minted to current block.timestamp (now)
poolTimeLastMinted = now;
}
/// @dev sets the address for the rewards pool
/// @param _newAddress pool Address
function setPool(address _newAddress) public onlyOwner {
pool = _newAddress;
}
////////////////////////////////
// Helper Functions
////////////////////////////////
/// @dev calculateFraction allows us to better handle the Solidity ugliness of not having decimals as a native type
/// @param _numerator is the top part of the fraction we are calculating
/// @param _denominator is the bottom part of the fraction we are calculating
/// @param _precision tells the function how many significant digits to calculate out to
/// @return quotient returns the result of our fraction calculation
function calculateFraction(uint _numerator, uint _denominator, uint _precision) pure private returns(uint quotient) {
// Take passed value and expand it to the required precision
_numerator = _numerator.mul(10 ** (_precision + 1));
// Handle last-digit rounding
uint _quotient = ((_numerator.div(_denominator)) + 5) / 10;
return (_quotient);
}
/// @dev Determines the amount of Scale to create based on the number of seconds that have passed
/// @param _timeInSeconds is the time passed in seconds to mint for
/// @return uint with the calculated number of new tokens to mint
function calculateMintTotal(uint _timeInSeconds, uint _mintRate) pure private returns(uint mintAmount) {
// Calculates the amount of tokens to mint based upon the number of seconds passed
return(_timeInSeconds.mul(_mintRate));
}
} | Last day the totalScaleStaked was updated
| uint _lastDayStakeWasUpdated; | 12,235,944 | [
1,
3024,
2548,
326,
2078,
5587,
510,
9477,
1703,
3526,
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,
1377,
2254,
389,
2722,
4245,
510,
911,
14992,
7381,
31,
282,
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.4.18;
import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
contract SubdomainRedirect is Ownable {
struct SubdomainEntry {
string redirect; // redirect url
address owner; // entry owner
uint registeredUntil; // timestamp until this registration is valid
}
uint public registrationFee = 1000000;
uint public registrations = 0;
uint public registrationPeriod = 1 years + 30 days;
mapping (string => SubdomainEntry) entries;
mapping (uint => string) names;
function createRegistration(string name, string redirect) external payable {
require(
msg.value >= registrationFee &&
(entries[name].owner == address(0) || entries[name].registeredUntil < now) &&
bytes(redirect).length > 0
);
entries[name].redirect = redirect;
entries[name].owner = msg.sender;
entries[name].registeredUntil = now + registrationPeriod;
names[registrations] = name;
registrations += 1;
}
function renewRegistration(string name) external payable {
require(
msg.value >= registrationFee &&
entries[name].owner == msg.sender
);
entries[name].registeredUntil = now + registrationPeriod;
}
function updateRegistration(string name, string redirect) external {
require(
entries[name].owner == msg.sender &&
entries[name].registeredUntil > now
);
entries[name].redirect = redirect;
}
function getRegistrationByIndex(uint index) public view returns (string, string, uint, address) {
require(
index >= 0 && index < registrations
);
string memory name = names[index];
return (name, entries[name].redirect, entries[name].registeredUntil, entries[name].owner);
}
function getRegistrationByName(string name) public view returns (string, string, uint, address) {
return (name, entries[name].redirect, entries[name].registeredUntil, entries[name].owner);
}
function clearRegistration(string name, bool full) onlyOwner external {
entries[name].redirect = "";
if (full) {
entries[name].owner = address(0);
entries[name].registeredUntil = 0;
}
}
} | timestamp until this registration is valid
| uint registeredUntil; | 1,069,423 | [
1,
5508,
3180,
333,
7914,
353,
923,
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,
2254,
4104,
9716,
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,
-100
] |
// File contracts/libraries/SafeMath.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
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 (uint c) {
if (a > 3) {
c = a;
uint 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;
}
}
}
// File contracts/libraries/Address.sol
pragma solidity 0.7.5;
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);
}
}
// File contracts/interfaces/IERC20.sol
pragma solidity 0.7.5;
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);
}
// File contracts/libraries/SafeERC20.sol
pragma solidity 0.7.5;
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");
}
}
}
// File contracts/libraries/FullMath.sol
pragma solidity 0.7.5;
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);
}
}
// File contracts/libraries/FixedPoint.sol
pragma solidity 0.7.5;
library Babylonian {
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
library BitMath {
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
}
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 (uint) {
return uint(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));
}
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
// File contracts/types/Ownable.sol
pragma solidity 0.7.5;
contract Ownable {
address public policy;
constructor () {
policy = msg.sender;
}
modifier onlyPolicy() {
require( policy == msg.sender, "Ownable: caller is not the owner" );
_;
}
function transferManagment(address _newOwner) external onlyPolicy() {
require( _newOwner != address(0) );
policy = _newOwner;
}
}
// File contracts/Bankless/CustomBond.sol
pragma solidity 0.7.5;
interface ITreasury {
function deposit(address _principleTokenAddress, uint _amountPrincipleToken, uint _amountPayoutToken) external;
function valueOfToken( address _principalTokenAddress, uint _amount ) external view returns ( uint value_ );
function payoutToken() external view returns (address);
}
contract CustomBANKBond is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint payout, uint expires );
event BondRedeemed( address recipient, uint payout, uint remaining );
event BondPriceChanged( uint internalPrice, uint debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
IERC20 immutable payoutToken; // token paid for principal
IERC20 immutable principalToken; // inflow token
ITreasury immutable customTreasury; // pays for and receives principal
address immutable olympusDAO;
address olympusTreasury; // receives fee
address immutable subsidyRouter; // pays subsidy in OHM to custom treasury
uint public totalPrincipalBonded;
uint public totalPayoutGiven;
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint public lastDecay; // reference block for debt decay
uint payoutSinceLastSubsidy; // principal accrued since subsidy paid
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
FeeTiers[] private feeTiers; // stores fee tiers
bool immutable private feeInPayout;
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
/* ======== STRUCTS ======== */
struct FeeTiers {
uint tierCeilings; // principal bonded till next tier
uint fees; // in ten-thousandths (i.e. 33300 = 3.33%)
}
// Info for creating new bonds
struct Terms {
uint controlVariable; // scaling variable for price
uint vestingTerm; // in blocks
uint minimumPrice; // vs principal value
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // payout token decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint payout; // payout token remaining to be paid
uint vesting; // Blocks left to vest
uint lastBlock; // Last interaction
uint truePricePaid; // Price paid (principal tokens per payout token) in ten-millionths - 4000000 = 0.4
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint buffer; // minimum length (in blocks) between adjustments
uint lastBlock; // block when last adjustment made
}
/* ======== CONSTRUCTOR ======== */
constructor(
address _customTreasury,
address _principalToken,
address _olympusTreasury,
address _subsidyRouter,
address _initialOwner,
address _olympusDAO,
uint[] memory _tierCeilings,
uint[] memory _fees,
bool _feeInPayout
) {
require( _customTreasury != address(0) );
customTreasury = ITreasury( _customTreasury );
payoutToken = IERC20( ITreasury(_customTreasury).payoutToken() );
require( _principalToken != address(0) );
principalToken = IERC20( _principalToken );
require( _olympusTreasury != address(0) );
olympusTreasury = _olympusTreasury;
require( _subsidyRouter != address(0) );
subsidyRouter = _subsidyRouter;
require( _initialOwner != address(0) );
policy = _initialOwner;
require( _olympusDAO != address(0) );
olympusDAO = _olympusDAO;
require(_tierCeilings.length == _fees.length, "tier length and fee length not the same");
for(uint i; i < _tierCeilings.length; i++) {
feeTiers.push( FeeTiers({
tierCeilings: _tierCeilings[i],
fees: _fees[i]
}));
}
feeInPayout = _feeInPayout;
}
/* ======== INITIALIZATION ======== */
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBond(
uint _controlVariable,
uint _vestingTerm,
uint _minimumPrice,
uint _maxPayout,
uint _maxDebt,
uint _initialDebt
) external onlyPolicy() {
require( currentDebt() == 0, "Debt must be 0 for initialization" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = block.number;
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _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;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment (
bool _addition,
uint _increment,
uint _target,
uint _buffer
) external onlyPolicy() {
require( _increment <= terms.controlVariable.mul( 30 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastBlock: block.number
});
}
/**
* @notice change address of Olympus Treasury
* @param _olympusTreasury uint
*/
function changeOlympusTreasury(address _olympusTreasury) external {
require( msg.sender == olympusDAO, "Only Olympus DAO" );
olympusTreasury = _olympusTreasury;
}
/**
* @notice subsidy controller checks payouts since last subsidy and resets counter
* @return payoutSinceLastSubsidy_ uint
*/
function paySubsidy() external returns ( uint payoutSinceLastSubsidy_ ) {
require( msg.sender == subsidyRouter, "Only subsidy controller" );
payoutSinceLastSubsidy_ = payoutSinceLastSubsidy;
payoutSinceLastSubsidy = 0;
}
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit(uint _amount, uint _maxPrice, address _depositor) external returns (uint) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
uint nativePrice = trueBondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = customTreasury.valueOfToken( address(principalToken), _amount );
uint payout;
uint fee;
if(feeInPayout) {
(payout, fee) = payoutFor( value ); // payout to bonder is computed
} else {
(payout, fee) = payoutFor( _amount ); // payout to bonder is computed
_amount = _amount.sub(fee);
}
require( payout >= 10 ** payoutToken.decimals() / 100, "Bond too small" ); // must be > 0.01 payout token ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
// total debt is increased
totalDebt = totalDebt.add( value );
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
// depositor info is stored
bondInfo[ _depositor ] = Bond({
payout: bondInfo[ _depositor ].payout.add( payout ),
vesting: terms.vestingTerm,
lastBlock: block.number,
truePricePaid: trueBondPrice()
});
totalPrincipalBonded = totalPrincipalBonded.add(_amount); // total bonded increased
totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased
payoutSinceLastSubsidy = payoutSinceLastSubsidy.add( payout ); // subsidy counter increased
principalToken.approve( address(customTreasury), _amount );
if(feeInPayout) {
principalToken.safeTransferFrom( msg.sender, address(this), _amount );
customTreasury.deposit( address(principalToken), _amount, payout.add(fee) );
} else {
principalToken.safeTransferFrom( msg.sender, address(this), _amount.add(fee) );
customTreasury.deposit( address(principalToken), _amount, payout );
}
if ( fee != 0 ) { // fee is transferred to dao
if(feeInPayout) {
payoutToken.safeTransfer(olympusTreasury, fee);
} else {
principalToken.safeTransfer( olympusTreasury, fee );
}
}
// indexed events are emitted
emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ) );
emit BondPriceChanged( _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @return uint
*/
function redeem(address _depositor) external returns (uint) {
Bond memory info = bondInfo[ _depositor ];
uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _depositor ]; // delete user info
emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data
payoutToken.safeTransfer( _depositor, info.payout );
return info.payout;
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _depositor ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),
lastBlock: block.number,
truePricePaid: info.truePricePaid
});
emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout );
payoutToken.safeTransfer( _depositor, payout );
return payout;
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );
if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {
uint 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;
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate true bond price a user pays
* @return price_ uint
*/
function trueBondPrice() public view returns ( uint price_ ) {
price_ = bondPrice().add(bondPrice().mul( currentOlympusFee() ).div( 1e6 ) );
}
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return payoutToken.totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate user's interest due for new bond, accounting for Olympus Fee.
If fee is in payout then takes in the already calcualted value. If fee is in principal token
than takes in the amount of principal being deposited and then calculautes the fee based on
the amount of principal and not in terms of the payout token
* @param _value uint
* @return _payout uint
* @return _fee uint
*/
function payoutFor( uint _value ) public view returns ( uint _payout, uint _fee) {
if(feeInPayout) {
uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 );
_fee = total.mul( currentOlympusFee() ).div( 1e6 );
_payout = total.sub(_fee);
} else {
_fee = _value.mul( currentOlympusFee() ).div( 1e6 );
_payout = FixedPoint.fraction( customTreasury.valueOfToken(address(principalToken), _value.sub(_fee)), bondPrice() ).decode112with18().div( 1e11 );
}
}
/**
* @notice calculate current ratio of debt to payout token supply
* @notice protocols using Olympus Pro should be careful when quickly adding large %s to total supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 10 ** payoutToken.decimals() ),
payoutToken.totalSupply()
).decode112with18().div( 1e18 );
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint 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 ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint blocksSinceLast = block.number.sub( bond.lastBlock );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of payout token available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = bondInfo[ _depositor ].payout;
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/**
* @notice current fee Olympus takes of each bond
* @return currentFee_ uint
*/
function currentOlympusFee() public view returns( uint currentFee_ ) {
uint tierLength = feeTiers.length;
for(uint i; i < tierLength; i++) {
if(totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1 ) {
return feeTiers[i].fees;
}
}
}
} | * @notice calculate true bond price a user pays @return price_ uint/ | function trueBondPrice() public view returns ( uint price_ ) {
price_ = bondPrice().add(bondPrice().mul( currentOlympusFee() ).div( 1e6 ) );
}
| 33,435 | [
1,
11162,
638,
8427,
6205,
279,
729,
293,
8271,
225,
327,
6205,
67,
2254,
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,
638,
9807,
5147,
1435,
1071,
1476,
1135,
261,
2254,
6205,
67,
262,
288,
203,
3639,
6205,
67,
273,
8427,
5147,
7675,
1289,
12,
26425,
5147,
7675,
16411,
12,
783,
51,
715,
1291,
407,
14667,
1435,
262,
18,
2892,
12,
404,
73,
26,
262,
11272,
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
] |
./full_match/1/0x78E3DD527D0F9d2c64e5ac2f7C1EC9384Da58803/sources/BSB_StakingSoftStakers.sol | 20% of weekly rewards earned
| uint percent_claim = 1; | 3,119,189 | [
1,
3462,
9,
434,
4860,
715,
283,
6397,
425,
1303,
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
] | [
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,
2254,
5551,
67,
14784,
273,
404,
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
] |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 rateLimit;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IDistributeV1
interface IDistributeV1 {
function claim(address _to, uint256 _earningsToDate, uint256 _nonce, bytes memory _signature) external;
}
// Part: IKToken
interface IKToken {
function underlying() external view returns (address);
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);
function mint(address recipient, uint256 amount) external returns (bool);
function burnFrom(address sender, uint256 amount) external;
function addMinter(address sender) external;
function renounceMinter() external;
}
// Part: IName
interface IName {
function name() external view returns (string memory);
}
// Part: IUniswapV2Router01
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: ILiquidityPool
interface ILiquidityPool {
function depositFeeInBips() external view returns (uint256);
function kToken(address _token) external view returns (IKToken);
function register(IKToken _kToken) external;
function renounceOperator() external;
function deposit(address _token, uint256 _amount) external payable returns (uint256);
function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external;
function borrowableBalance(address _token) external view returns (uint256);
function underlyingBalance(address _token, address _owner) external view returns (uint256);
}
// Part: IUniswapV2Router02
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient)
external
returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient)
external
returns (uint256);
function token() external view returns (address);
function strategies(address _strategy)
external
view
returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: BaseStrategyEdited
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategyEdited {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.0";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding
);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI)
external
onlyAuthorized
{
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return
vault.strategies(address(this)).debtRatio > 0 ||
estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded)
internal
virtual
returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost)
public
view
virtual
returns (bool)
{
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay)
return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay)
return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(
totalAssets > debtOutstanding ? totalAssets : debtOutstanding
);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategyEdited(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++)
require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(
governance(),
IERC20(_token).balanceOf(address(this))
);
}
}
// Part: BaseStrategyInitializable
abstract contract BaseStrategyInitializable is BaseStrategyEdited {
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategyEdited(_vault) {}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function clone(address _vault) external returns (address) {
return this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
BaseStrategyInitializable(newStrategy).initialize(
_vault,
_strategist,
_rewards,
_keeper
);
emit Cloned(newStrategy);
}
}
// File: Strategy.sol
contract Strategy is BaseStrategyInitializable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IUniswapV2Router02 constant public uniswapRouter = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
IUniswapV2Router02 constant public sushiswapRouter = IUniswapV2Router02(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F));
IERC20 public constant weth = IERC20(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2));
IERC20 public constant rook = IERC20(address(0xfA5047c9c78B8877af97BDcb85Db743fD7313d4a));
IUniswapV2Router02 public router;
IDistributeV1 public distributor;
IKToken public kToken;
ILiquidityPool public pool;
address public treasury;
address[] public path;
address[] public wethWantPath;
// unsigned. Indicates the losses incurred from the protocol's deposit fees
uint256 public incurredLosses;
// amount to send to treasury. Used for future governance voting power
uint256 public percentKeep;
uint256 public constant _denominator = 10000;
bool public isSunset;
constructor(address _vault,
address _strategist,
address _rewards,
address _keeper,
address _pool,
address _voter,
address _rewardDistributor,
address payable _oldStrategy
) public BaseStrategyInitializable(_vault) {
_init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor, _oldStrategy);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _pool,
address _voter,
address _rewardDistributor,
address payable _oldStrategy
) external returns (address payable newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor, _oldStrategy);
emit Cloned(newStrategy);
}
function init(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _pool,
address _voter,
address _rewardDistributor,
address payable _oldStrategy
) external {
super._initialize(_vault, _strategist, _rewards, _keeper);
_init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor, _oldStrategy);
}
function _init(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _pool,
address _voter,
address _rewardDistributor,
address payable _oldStrategy
) internal {
// If this strategy is migrated from a previous rook strategy, set the appropriate _oldStrategy
// address in order to transfer the internal account (_incurredLosses) over,
// otherwise it should be the zero address and bypass this step
if (_oldStrategy != address(0x0)) {
Strategy _oldStrategy = Strategy(_oldStrategy);
require(_oldStrategy.want() == want, "want mismatch");
incurredLosses = _oldStrategy.incurredLosses();
}
// check to see if KeeperDao can actually accept want (renBTC, DAI, USDC, ETH, WETH)
pool = ILiquidityPool(address(_pool));
kToken = pool.kToken(address(want));
require(address(kToken) != address(0x0), "Protocol doesn't support this token!");
want.safeApprove(address(pool), uint256(- 1));
kToken.approve(address(pool), uint256(- 1));
treasury = address(_voter);
router = uniswapRouter;
rook.approve(address(uniswapRouter), uint256(- 1));
rook.approve(address(sushiswapRouter), uint256(- 1));
distributor = IDistributeV1(address(_rewardDistributor));
if (address(want) == address(weth)) {
path = [address(rook), address(weth)];
} else {
path = [address(rook), address(weth), address(want)];
wethWantPath = [address(weth), address(want)];
}
}
function name() external view override returns (string memory) {
return string(
abi.encodePacked("StrategyRook ", IName(address(want)).name())
);
}
function estimatedTotalAssets() public view override returns (uint256) {
return valueOfStaked().add(balanceOfUnstaked()).add(valueOfReward());
}
function balanceOfUnstaked() public view returns (uint256){
return want.balanceOf(address(this));
}
// valued in wants
function valueOfStaked() public view returns (uint256){
return pool.underlyingBalance(address(want), address(this));
}
// kTokens have different virtual prices. Balance != want
function balanceOfStaked() public view returns (uint256){
return kToken.balanceOf(address(this));
}
function balanceOfReward() public view returns (uint256){
return rook.balanceOf(address(this));
}
function valueOfReward() public view returns (uint256){
return _estimateAmountsOut(rook.balanceOf(address(this)), path);
}
// only way to find out is thru calculating a virtual price this way
function _inKTokens(uint256 wantAmount) internal view returns (uint256){
return wantAmount.mul(balanceOfStaked()).div(valueOfStaked());
}
function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){
// NOTE: Return `_profit` which is value generated by all positions, priced in `want`
// NOTE: Should try to free up at least `_debtOutstanding` of underlying position
// sell any reward, leave some for treasury
uint256 rewards = balanceOfReward();
if (rewards > 0) {
uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator);
if (rewardsForVoting > 0) {
IERC20(rook).safeTransfer(treasury, rewardsForVoting);
}
uint256 rewardsRemaining = balanceOfReward();
if (rewardsRemaining > 0) {
_sell(rewardsRemaining);
}
}
// from selling rewards
uint256 profit = balanceOfUnstaked();
// this should be guaranteed if called by keeper. See {harvestTrigger()}
if (profit > incurredLosses) {
// we want strategy to pay off its own incurredLosses from deposit fees first so it doesn't have to report _loss to the vault
_profit = profit.sub(incurredLosses);
} else {
_loss = incurredLosses.sub(profit);
}
// loss has been recorded.
incurredLosses = 0;
if (_debtOutstanding > 0) {
// withdraw just enough to pay off debt
uint256 _toWithdraw = Math.min(_debtOutstanding, valueOfStaked());
pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw));
uint256 _unstakedWithoutProfit = balanceOfUnstaked().sub(_profit);
if (_debtOutstanding > _unstakedWithoutProfit) {
_debtPayment = _unstakedWithoutProfit;
_loss = _debtOutstanding.sub(_unstakedWithoutProfit);
if (_profit > _loss) {
_profit = _profit.sub(_loss);
_loss = 0;
} else {
_loss = _loss.sub(_profit);
_profit = 0;
}
} else {
_debtPayment = _debtOutstanding;
_loss = 0;
}
}
// sunset scenario
if (isSunset && vault.strategies(address(this)).debtRatio == 0) {
uint256 _staked = balanceOfStaked();
if (_staked > 0) {
uint256 _before = balanceOfUnstaked();
pool.withdraw(address(this), kToken, _staked);
uint256 _after = balanceOfUnstaked();
uint256 _delta = _after.sub(_before);
if (_delta > _loss) {
_profit = _profit.add(_delta.sub(_loss));
_loss = 0;
} else {
_loss = _loss.sub(_delta);
_profit = 0;
}
}
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
// NOTE: Try to adjust positions so that `_debtOutstanding` can be freed up on *next* harvest (not immediately)
// deposit any loose balance
uint256 unstaked = balanceOfUnstaked();
if (unstaked > 0) {
_provideLiquidity(unstaked);
}
}
// NAV premium of 0.64% when depositing everytime. Need to keep track of this for _loss calculation.
function _provideLiquidity(uint256 _amount) private {
uint256 stakedBefore = valueOfStaked();
pool.deposit(address(want), _amount);
uint256 stakedAfter = valueOfStaked();
uint256 stakedDelta = stakedAfter.sub(stakedBefore);
uint256 depositFee = _amount.sub(stakedDelta);
incurredLosses = incurredLosses.add(depositFee);
}
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) {
// if _amountNeeded is more than currently available, need to unstake some and/or sell rewards to free up assets
uint256 unstaked = balanceOfUnstaked();
if (_amountNeeded > unstaked) {
uint256 desiredWithdrawAmount = _amountNeeded.sub(unstaked);
// can't withdraw more than staked
uint256 actualWithdrawAmount = Math.min(desiredWithdrawAmount, valueOfStaked());
pool.withdraw(address(this), kToken, _inKTokens(actualWithdrawAmount));
_liquidatedAmount = balanceOfUnstaked();
// already withdrew all that it could, any difference left is considered _loss,
// which is possible because of KeeperDao's initial deposit NAV premium of 0.64%
// i.e initial 10,000 deposit -> 9,936 in pool. If withdraw immediately, _loss = 64
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
// already have all of _amountNeeded unstaked
_liquidatedAmount = _amountNeeded;
_loss = 0;
}
return (_liquidatedAmount, _loss);
}
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
// Since claiming reward is done asynchronously, rewards could sit idle in strategy before next harvest() call
// See {claimRewards()} for detail
function prepareMigration(address _newStrategy) internal override {
kToken.transfer(_newStrategy, balanceOfStaked());
rook.transfer(_newStrategy, balanceOfReward());
}
// Trigger harvest only if strategy has rewards, otherwise, there's nothing to harvest.
// This logic is added on top of existing gas efficient harvestTrigger() in the parent class
function harvestTrigger(uint256 callCost) public override view returns (bool) {
return super.harvestTrigger(_estimateAmountsOut(callCost, wethWantPath)) && balanceOfReward() > 0 && netPositive();
}
// Indicator for whether strategy has earned enough rewards to offset incurred losses.
// Adding this to harvestTrigger() will ensure that strategy will never have to report a positive _loss to the vault and lower its trust
function netPositive() public view returns (bool){
return valueOfReward() > incurredLosses;
}
// Has to be called manually since this requires off-chain data.
// Needs to be called before harvesting otherwise there's nothing to harvest.
function claimRewards(uint256 _earningsToDate, uint256 _nonce, bytes memory _signature) external onlyKeepers {
require(_earningsToDate > 0, "You are trying to claim 0 rewards");
distributor.claim(address(this), _earningsToDate, _nonce, _signature);
}
function claimRewards(uint256 _earningsToDate, uint256 _nonce, bytes memory _signature, address _distributor) external onlyKeepers {
require(_earningsToDate > 0, "You are trying to claim 0 rewards");
IDistributeV1(address(_distributor)).claim(address(this), _earningsToDate, _nonce, _signature);
}
function sellSome(uint256 _amount) external onlyAuthorized {
require(_amount <= balanceOfReward());
_sell(_amount);
}
function _sell(uint256 _amount) internal {
// since claiming is async, no point in selling if strategy hasn't claimed rewards
router.swapExactTokensForTokens(_amount, uint256(0), path, address(this), now);
}
function _estimateAmountsOut(uint256 _amount, address[] memory sellPath) public view returns (uint256){
uint256 amountOut = 0;
if (sellPath.length <= 0) {
return _amount;
}
if (_amount > 0) {
amountOut = router.getAmountsOut(_amount, sellPath)[sellPath.length - 1];
}
return amountOut;
}
function protectedTokens() internal view override returns (address[] memory){
address[] memory protected = new address[](2);
protected[0] = address(kToken);
protected[1] = address(rook);
return protected;
}
function setKeep(uint256 _percentKeep) external onlyGovernance {
percentKeep = _percentKeep;
}
function setDistributor(address _distributor) external onlyGovernance {
distributor = IDistributeV1(address(_distributor));
}
function setTreasury(address _treasury) external onlyGovernance {
treasury = _treasury;
}
function setLiquidityPool(address _pool) external onlyGovernance {
want.safeApprove(address(_pool), uint256(- 1));
kToken.approve(address(_pool), uint256(- 1));
pool = ILiquidityPool(_pool);
}
function setIncurredLosses(uint256 _incurredLosses) external onlyGovernance {
incurredLosses = _incurredLosses;
}
function setSunset(bool _isSunset) external onlyGovernance {
isSunset = _isSunset;
}
function currentDepositFee() external view returns (uint256){
return pool.depositFeeInBips();
}
function switchDex(bool isUniswap) external onlyAuthorized {
if (isUniswap) router = uniswapRouter;
else router = sushiswapRouter;
}
receive() external payable {}
}
| * @notice Harvests the Strategy, recognizing any profits or losses and adjusting the Strategy's position. In the rare case the Strategy is in emergency shutdown, this will exit the Strategy's position. This may only be called by governance, the strategist, or the keeper. @dev When `harvest()` is called, the Strategy reports to the Vault (via `vault.report()`), so in some cases `harvest()` must be called in order to take in profits, to borrow newly available funds from the Vault, or otherwise adjust its position. In other cases `harvest()` must be called to report to the Vault on the Strategy's position, especially if any losses have occurred./ Free up as much capital as possible NOTE: use the larger of total assets or debt outstanding to book losses properly NOTE: take up any remainder here as profit | function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
uint256 totalAssets = estimatedTotalAssets();
(debtPayment, loss) = liquidatePosition(
totalAssets > debtOutstanding ? totalAssets : debtOutstanding
);
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
| 385,872 | [
1,
44,
297,
90,
25563,
326,
19736,
16,
14603,
6894,
1281,
9214,
1282,
578,
24528,
471,
5765,
310,
225,
326,
19736,
1807,
1754,
18,
225,
657,
326,
25671,
648,
326,
19736,
353,
316,
801,
24530,
5731,
16,
333,
903,
2427,
225,
326,
19736,
1807,
1754,
18,
225,
1220,
2026,
1338,
506,
2566,
635,
314,
1643,
82,
1359,
16,
326,
609,
1287,
376,
16,
578,
326,
417,
9868,
18,
282,
5203,
1375,
30250,
26923,
20338,
353,
2566,
16,
326,
19736,
10557,
358,
326,
17329,
261,
21985,
225,
1375,
26983,
18,
6006,
20338,
3631,
1427,
316,
2690,
6088,
1375,
30250,
26923,
20338,
1297,
506,
2566,
316,
1353,
225,
358,
4862,
316,
9214,
1282,
16,
358,
29759,
10894,
2319,
284,
19156,
628,
326,
17329,
16,
578,
225,
3541,
5765,
2097,
1754,
18,
657,
1308,
6088,
1375,
30250,
26923,
20338,
1297,
506,
225,
2566,
358,
2605,
358,
326,
17329,
603,
326,
19736,
1807,
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,
565,
445,
17895,
26923,
1435,
3903,
1338,
11523,
414,
288,
203,
3639,
2254,
5034,
450,
7216,
273,
374,
31,
203,
3639,
2254,
5034,
8324,
273,
374,
31,
203,
3639,
2254,
5034,
18202,
88,
1182,
15167,
273,
9229,
18,
323,
23602,
1182,
15167,
5621,
203,
3639,
2254,
5034,
18202,
88,
6032,
273,
374,
31,
203,
3639,
309,
261,
351,
24530,
6767,
13,
288,
203,
5411,
2254,
5034,
2078,
10726,
273,
13137,
5269,
10726,
5621,
203,
5411,
261,
323,
23602,
6032,
16,
8324,
13,
273,
4501,
26595,
340,
2555,
12,
203,
7734,
2078,
10726,
405,
18202,
88,
1182,
15167,
692,
2078,
10726,
294,
18202,
88,
1182,
15167,
203,
5411,
11272,
203,
5411,
309,
261,
323,
23602,
6032,
405,
18202,
88,
1182,
15167,
13,
288,
203,
7734,
450,
7216,
273,
18202,
88,
6032,
18,
1717,
12,
323,
23602,
1182,
15167,
1769,
203,
7734,
18202,
88,
6032,
273,
18202,
88,
1182,
15167,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
203,
203,
3639,
3626,
670,
297,
90,
3149,
12,
685,
7216,
16,
8324,
16,
18202,
88,
6032,
16,
18202,
88,
1182,
15167,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-13
*/
/**
LORD L - https://t.me/LORDLETH
*/
// SPDX-License-Identifier: unlicense
pragma solidity ^0.8.7;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
contract LORDL is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Lord Lawliet";//
string private constant _symbol = "LAWLIET";//
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public launchBlock;
//Buy Fee
uint256 private _redisFeeOnBuy = 0;//
uint256 private _taxFeeOnBuy = 5;//
//Sell Fee
uint256 private _redisFeeOnSell = 0;//
uint256 private _taxFeeOnSell = 15;//
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0x628964fCB3d3070f0BcEb5Acb05232d533bE276e);//
address payable private _marketingAddress = payable(0x628964fCB3d3070f0BcEb5Acb05232d533bE276e);//
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 33000000000 * 10**9; //
uint256 public _maxWalletSize = 33000000000 * 10**9; //
uint256 public _swapTokensAtAmount = 100000000 * 10**9; //
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);//
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
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 _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 (from != owner() && to != owner()) {
//Trade start check
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
launchBlock = block.number;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set maximum transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | Buy FeeSell FeeOriginal Fee | contract LORDL is Context, IERC20, Ownable {
using SafeMath for uint256;
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public launchBlock;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
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 _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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
} else {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock+1 && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
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);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
launchBlock = block.number;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | 15,188,938 | [
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
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,
16351,
511,
916,
8914,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
7010,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
7010,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
15088,
9449,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
565,
2254,
5034,
1071,
8037,
1768,
31,
203,
7010,
7010,
7010,
565,
2254,
5034,
3238,
389,
12311,
14667,
273,
389,
12311,
14667,
1398,
55,
1165,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
273,
389,
8066,
14667,
1398,
55,
1165,
31,
203,
7010,
565,
2254,
5034,
3238,
389,
11515,
12311,
14667,
273,
389,
12311,
14667,
31,
203,
565,
2254,
5034,
3238,
389,
1484,
522,
83,
641,
651,
14667,
273,
389,
8066,
14667,
31,
203,
7010,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
2512,
87,
31,
203,
565,
2874,
12,
2867,
2
] |
./full_match/42/0x19f5981C05cC486d8706d3D691644B0465AaB87E/sources/browser/gists/536123b71478ad4442cfc4278e8de577/RandomNumberConsumer.sol | * Callback function used by VRF Coordinator/ | function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomResult = randomness;
uint256 totalAmount = 0;
for (uint i=0; i<entries.length; i++) {
totalAmount = totalAmount + entries[i].amount;
}
uint256 winningNumber = randomness % totalAmount;
for (uint i=0; i<entries.length; i++) {
totalAmount = totalAmount + entries[i].amount;
if (winningNumber <= totalAmount) {
winningAddress = entries[i].adr;
break;
}
}
owner.transfer(address(this).balance / 100);
emit NewWinner(winningAddress, address(this).balance, runNumber);
winningAddress.transfer(address(this).balance);
runNumber = runNumber + 1;
delete entries;
}
| 16,206,612 | [
1,
2428,
445,
1399,
635,
776,
12918,
10320,
4240,
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
] | [
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,
22290,
8529,
4496,
12,
3890,
1578,
14459,
16,
2254,
5034,
2744,
4496,
13,
2713,
3849,
288,
203,
3639,
2744,
1253,
273,
2744,
4496,
31,
203,
540,
203,
3639,
2254,
5034,
2078,
6275,
273,
374,
31,
203,
3639,
364,
261,
11890,
277,
33,
20,
31,
277,
32,
8219,
18,
2469,
31,
277,
27245,
288,
203,
1850,
2078,
6275,
273,
2078,
6275,
397,
3222,
63,
77,
8009,
8949,
31,
203,
3639,
289,
203,
540,
203,
3639,
2254,
5034,
5657,
2093,
1854,
273,
2744,
4496,
738,
2078,
6275,
31,
203,
203,
3639,
364,
261,
11890,
277,
33,
20,
31,
277,
32,
8219,
18,
2469,
31,
277,
27245,
288,
203,
1850,
2078,
6275,
273,
2078,
6275,
397,
3222,
63,
77,
8009,
8949,
31,
203,
1850,
309,
261,
8082,
2093,
1854,
1648,
2078,
6275,
13,
288,
203,
2868,
5657,
2093,
1887,
273,
3222,
63,
77,
8009,
361,
86,
31,
203,
2868,
898,
31,
203,
1850,
289,
203,
3639,
289,
203,
540,
203,
540,
203,
3639,
3410,
18,
13866,
12,
2867,
12,
2211,
2934,
12296,
342,
2130,
1769,
203,
540,
203,
3639,
3626,
1166,
59,
7872,
12,
8082,
2093,
1887,
16,
1758,
12,
2211,
2934,
12296,
16,
1086,
1854,
1769,
203,
540,
203,
3639,
5657,
2093,
1887,
18,
13866,
12,
2867,
12,
2211,
2934,
12296,
1769,
203,
3639,
1086,
1854,
273,
1086,
1854,
397,
404,
31,
203,
3639,
1430,
3222,
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
] |
./full_match/1/0xBC11De1F20e83F0a6889B8c7A7868E722694E315/sources/submodules/v2-foundry/src/external/aave/StaticAToken.sol | * @dev Converts an aToken or underlying amount to the what it is denominated on the aToken as scaled balance, function of the principal and the liquidity index @param amount The amount to convert from @return uint256 The static (scaled) amount/ | function dynamicToStaticAmount(uint256 amount) public view returns (uint256) {
return amount.rayDiv(rate());
}
| 3,018,082 | [
1,
5692,
392,
279,
1345,
578,
6808,
3844,
358,
326,
4121,
518,
353,
10716,
7458,
603,
326,
279,
1345,
487,
12304,
11013,
16,
445,
434,
326,
8897,
471,
326,
4501,
372,
24237,
770,
225,
3844,
1021,
3844,
358,
1765,
628,
327,
2254,
5034,
1021,
760,
261,
20665,
13,
3844,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
5976,
774,
5788,
6275,
12,
11890,
5034,
3844,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
3844,
18,
435,
7244,
12,
5141,
10663,
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
] |
./full_match/1/0xe5b9239A8be521C9A08ba9A4b925DFa86Ee19024/sources/contracts/CopyPasta.sol | @notice Sets an account exclusion or inclusion from fees. @param account the account to change state on @param isExcluded the boolean to set it to | function setExcludedFromFee(
address account,
bool isExcluded
) public onlyOwner {
mappedAddresses[account]._isExcludedFromFee = isExcluded;
}
| 2,950,194 | [
1,
2785,
392,
2236,
21244,
578,
26485,
628,
1656,
281,
18,
225,
2236,
326,
2236,
358,
2549,
919,
603,
225,
353,
16461,
326,
1250,
358,
444,
518,
358,
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
] | [
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
444,
16461,
1265,
14667,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
1426,
353,
16461,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
5525,
7148,
63,
4631,
65,
6315,
291,
16461,
1265,
14667,
273,
353,
16461,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "ERC721Enumerable.sol";
import "SafeMath.sol";
import "Counters.sol";
import "Ownable.sol";
import "Pausable.sol";
import "BPC.sol";
import "BPCSenderRecipient.sol";
import "ExternalFuncs.sol";
contract BPCLottery is ERC721, ERC777SenderRecipientMock, Ownable, Pausable {
//using ExternalFuncs for *;
using Counters for Counters.Counter;
using SafeMath for uint256;
IERC777 private m_bpc;
bool private m_bpc_is_set;
modifier isTokenSet() {
require(m_bpc_is_set, "ERC777 is not set");
_;
}
address private m_company_account;
Counters.Counter private m_ticket_id;
Counters.Counter private m_lottery_id;
uint256 private m_ticket_price;
bool private is_lottery_open;
uint256 private constant m_duration = 7 days;
struct Winner {
uint256 ticket_id;
address addr;
bool isSet;
}
mapping(uint256 => uint256) private m_lottery_id_pot;
mapping(uint256 => uint256) private m_lottery_id_expires_at;
mapping(uint256 => bool) private m_lottery_id_paid;
mapping(uint256 => Winner) private m_lottery_id_winner;
event WinnerAnnounced(
address winner,
uint256 winner_id,
uint256 lottery_id,
uint256 prize_size
);
event WinnerPaid(address winner, uint256 lottery_id, uint256 prize_size);
constructor(
string memory _name,
string memory _symbol,
uint256 _ticket_price,
address _company_account
) ERC721(_name, _symbol) {
m_company_account = _company_account;
// ERC-777 receiver init
// See https://forum.openzeppelin.com/t/simple-erc777-token-example/746
_erc1820.setInterfaceImplementer(
address(this),
_TOKENS_RECIPIENT_INTERFACE_HASH,
address(this)
);
m_ticket_price = _ticket_price != 0
? _ticket_price
: 5000000000000000000; // 5 * 10^18
m_lottery_id_expires_at[m_lottery_id.current()] = block.timestamp.add(
m_duration
);
m_lottery_id_paid[m_lottery_id.current()] = false;
is_lottery_open = true;
m_bpc_is_set = false;
}
function setERC777(address _bpc) public onlyOwner {
require(_bpc != address(0), "BPC address cannot be 0");
require(
!m_bpc_is_set,
"You have already set BPC address, can't do it again"
);
m_bpc = IERC777(_bpc);
m_bpc_is_set = true;
}
function pause() public onlyOwner whenNotPaused {
_pause();
}
function unPause() public onlyOwner whenPaused {
_unpause();
}
//function paused() public view comes as a base class method of Pausable
function setTicketPrice(uint256 new_ticket_price)
public
onlyOwner
isTokenSet
{
require(new_ticket_price > 0, "Ticket price should be greater than 0");
m_ticket_price = new_ticket_price;
}
//when not paused
function getTicketPrice() public view returns (uint256) {
require(!paused(), "Lottery is paused, please come back later");
return m_ticket_price;
}
//when not paused
function buyTicket(uint256 bpc_tokens_amount, address participant)
public
isTokenSet
{
require(!paused(), "Lottery is paused, please come back later");
require(
m_bpc.isOperatorFor(msg.sender, participant),
"You MUST be an operator for participant"
);
require(
bpc_tokens_amount.mod(m_ticket_price) == 0,
"Tokens amount should be a multiple of a Ticket Price"
);
require(
m_bpc.balanceOf(participant) >= bpc_tokens_amount,
"You should have enough of Tokens in your Wallet"
);
m_bpc.operatorSend(
participant,
address(this),
bpc_tokens_amount,
bytes(""),
bytes("")
);
m_lottery_id_pot[m_lottery_id.current()] = m_lottery_id_pot[
m_lottery_id.current()
].add(bpc_tokens_amount);
uint256 tickets_count = bpc_tokens_amount.div(m_ticket_price);
for (uint256 i = 0; i != tickets_count; ++i) {
m_ticket_id.increment();
_mint(participant, m_ticket_id.current());
}
}
//when not paused
function getCurrentLotteryTicketsCount(address participant)
public
view
returns (uint256)
{
require(!paused(), "Lottery is paused, please come back later");
require(
m_bpc.isOperatorFor(msg.sender, participant),
"You MUST be an operator for participant"
);
return this.balanceOf(participant);
}
function getCurrentLotteryId() public view returns (uint256) {
return m_lottery_id.current();
}
function getCurrentLotteryPot() public view returns (uint256) {
return m_lottery_id_pot[m_lottery_id.current()];
}
function announceWinnerAndRevolve() public onlyOwner isTokenSet {
require(isLotteryPeriodOver(), "The current lottery is still running");
forceAnnounceWinnerAndRevolve();
}
function forceAnnounceWinnerAndRevolve() public onlyOwner isTokenSet {
uint256 prize_size = m_lottery_id_pot[m_lottery_id.current()].div(2);
uint256 id = m_lottery_id.current();
if (!m_lottery_id_winner[id].isSet) {
m_lottery_id_winner[id] = setWinner(prize_size);
}
if (!isEmptyWinner(m_lottery_id_winner[id]) && !m_lottery_id_paid[id]) {
splitPotWith(m_lottery_id_winner[id].addr, prize_size);
m_lottery_id_paid[id] = true;
m_lottery_id_pot[id] = 0;
}
if (!paused()) {
revolveLottery();
}
}
function isLotteryPeriodOver() private view returns (bool) {
return
m_lottery_id_expires_at[m_lottery_id.current()] < block.timestamp;
}
function getWinner(uint256 id) public view returns (address) {
require(
m_lottery_id_winner[id].isSet,
"Lottery Id Winner or Lottery Id not found"
);
return m_lottery_id_winner[id].addr;
}
function setWinner(uint256 prize_size) private returns (Winner memory) {
Winner memory winner;
winner.isSet = true;
if (m_ticket_id.current() != 0) {
winner.ticket_id = prng().mod(m_ticket_id.current()).add(1);
winner.addr = this.ownerOf(winner.ticket_id);
emit WinnerAnnounced(
winner.addr,
winner.ticket_id,
m_lottery_id.current(),
prize_size
);
} else {
winner.ticket_id = 0;
winner.addr = address(0);
}
return winner;
}
function isEmptyWinner(Winner memory winner) private pure returns (bool) {
return winner.addr == address(0);
}
function splitPotWith(address winner_address, uint256 prize_size) private {
m_bpc.operatorSend(
address(this),
winner_address,
prize_size,
bytes(""),
bytes("")
);
m_bpc.operatorSend(
address(this),
m_company_account,
prize_size,
bytes(""),
bytes("")
);
emit WinnerPaid(winner_address, m_lottery_id.current(), prize_size);
}
function revolveLottery() private {
uint256 size = m_ticket_id.current();
if (size != 0) {
for (uint256 i = 1; i <= size; ++i) {
_burn(i);
}
}
m_ticket_id.reset();
m_lottery_id.increment();
m_lottery_id_expires_at[m_lottery_id.current()] = block.timestamp.add(
m_duration
);
}
function prng() private view returns (uint256) {
return
uint256(
keccak256(
abi.encodePacked(
block.difficulty,
block.timestamp,
m_ticket_id.current()
)
)
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "ERC721.sol";
import "IERC721Enumerable.sol";
/**
* @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();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract 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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
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
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.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.8.10;
import "ERC777.sol";
import "AccessControl.sol";
import "SafeMath.sol";
import "ReentrancyGuard.sol";
contract BPC is ERC777, AccessControl, ReentrancyGuard {
using SafeMath for uint256;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint256 private constant m_tokens_per_eth = 100;
address private m_company_account;
uint256 private m_entry_fee;
uint256 private m_exit_fee;
uint256 private m_max_supply;
constructor(
string memory _name,
string memory _symbol,
address[] memory _default_operators,
uint256 _max_supply,
uint256 _initial_supply,
uint256 _entry_fee,
uint256 _exit_fee,
address _managing_account,
address _company_account
) ERC777(_name, _symbol, _default_operators) {
_grantRole(DEFAULT_ADMIN_ROLE, _managing_account);
_grantRole(MINTER_ROLE, _company_account);
m_max_supply = _max_supply;
_mint(_company_account, _initial_supply, "", "", false);
m_company_account = _company_account;
m_entry_fee = _entry_fee;
m_exit_fee = _exit_fee;
}
function mint(uint256 amount) public onlyRole(MINTER_ROLE) {
require(
totalSupply().add(amount) <= m_max_supply,
"Amount that is about to be minted reaches the Max Supply"
);
_mint(msg.sender, amount, bytes(""), bytes(""), false);
}
//burn and operatorBurn of ERC777 make all required checks and update _totalSupply that holds current Tokens qty
//no need to override those funcs
function fromEtherToTokens() public payable {
uint256 tokens_to_buy = msg.value * m_tokens_per_eth;
uint256 company_token_balance = this.balanceOf(m_company_account);
require(
tokens_to_buy > 0,
"You need to send some more ether, what you provide is not enough for transaction"
);
require(
tokens_to_buy <= company_token_balance,
"Not enough tokens in the reserve"
);
uint256 updated_value = getEntryFeeValue(tokens_to_buy);
_send(
m_company_account,
msg.sender,
updated_value,
bytes(""),
bytes(""),
false
);
}
function fromTokensToEther(uint256 tokens_to_sell) public nonReentrant {
require(tokens_to_sell > 0, "You need to sell at least some tokens");
// Check that the user's token balance is enough to do the swap
uint256 user_token_balance = this.balanceOf(msg.sender);
require(
user_token_balance >= tokens_to_sell,
"Your balance is lower than the amount of tokens you want to sell"
);
uint256 updated_value = getExitFeeValue(tokens_to_sell);
uint256 eth_to_transfer = updated_value / m_tokens_per_eth;
uint256 company_eth_balance = address(this).balance;
require(
company_eth_balance >= eth_to_transfer,
"BPC Owner doesn't have enough funds to accept this sell request"
);
_send(
msg.sender,
m_company_account,
tokens_to_sell,
bytes(""),
bytes(""),
false
);
payable(msg.sender).transfer(eth_to_transfer);
}
function getTokenPrice() public view returns (uint256) {
return m_tokens_per_eth;
}
function getEntryFee() public view returns (uint256) {
return m_entry_fee;
}
function getExitFee() public view returns (uint256) {
return m_exit_fee;
}
function setEntryFee(uint256 fee) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(
fee >= 0 && fee <= 100,
"Fee must be an integer percentage, ie 42"
);
m_entry_fee = fee;
}
function setExitFee(uint256 fee) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(
fee >= 0 && fee <= 100,
"Fee must be an integer percentage, ie 42"
);
m_exit_fee = fee;
}
function getEntryFeeValue(uint256 value) private view returns (uint256) {
if (m_entry_fee != 0) {
uint256 fee_value = (m_entry_fee * value) / 100;
uint256 updated_value = value - fee_value;
return updated_value;
} else {
return value;
}
}
function getExitFeeValue(uint256 value) private view returns (uint256) {
if (m_exit_fee != 0) {
uint256 fee_value = (m_exit_fee * value) / 100;
uint256 updated_value = value - fee_value;
return updated_value;
} else {
return value;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/ERC777.sol)
pragma solidity ^0.8.0;
import "IERC777.sol";
import "IERC777Recipient.sol";
import "IERC777Sender.sol";
import "IERC20.sol";
import "Address.sol";
import "Context.sol";
import "IERC1820Registry.sol";
/**
* @dev Implementation of the {IERC777} 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}.
*
* 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.
*/
contract ERC777 is Context, IERC777, IERC20 {
using Address for address;
IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender");
bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping(address => mapping(address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name_,
string memory symbol_,
address[] memory defaultOperators_
) {
_name = name_;
_symbol = symbol_;
_defaultOperatorsArray = defaultOperators_;
for (uint256 i = 0; i < defaultOperators_.length; i++) {
_defaultOperators[defaultOperators_[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(
address recipient,
uint256 amount,
bytes memory data
) public virtual override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public virtual override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) {
return
operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public virtual override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public virtual override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view virtual override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
) public virtual override {
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(
address account,
uint256 amount,
bytes memory data,
bytes memory operatorData
) public virtual override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view virtual override 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) public virtual override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
uint256 currentAllowance = _allowances[holder][spender];
require(currentAllowance >= amount, "ERC777: transfer amount exceeds allowance");
_approve(holder, spender, currentAllowance - amount);
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) internal virtual {
_mint(account, amount, userData, operatorData, true);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If `requireReceptionAck` is set to true, and if a send hook is
* registered for `account`, the corresponding function will be called with
* `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal virtual {
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply += amount;
_balances[account] += amount;
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal virtual {
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
) internal virtual {
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
// Update state variables
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC777: burn amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_totalSupply -= amount;
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
_beforeTokenTransfer(operator, from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC777: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(
address holder,
address spender,
uint256 value
) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
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 if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) private {
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(
address recipient,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Sender.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(
address account,
bytes32 _interfaceHash,
address implementer
) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "IAccessControl.sol";
import "Context.sol";
import "Strings.sol";
import "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 revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC777.sol";
import "IERC777Sender.sol";
import "IERC777Recipient.sol";
import "Context.sol";
import "IERC1820Registry.sol";
import "ERC1820Implementer.sol";
contract ERC777SenderRecipientMock is Context, IERC777Sender, IERC777Recipient, ERC1820Implementer {
event TokensToSendCalled(
address operator,
address from,
address to,
uint256 amount,
bytes data,
bytes operatorData,
address token,
uint256 fromBalance,
uint256 toBalance
);
event TokensReceivedCalled(
address operator,
address from,
address to,
uint256 amount,
bytes data,
bytes operatorData,
address token,
uint256 fromBalance,
uint256 toBalance
);
// Emitted in ERC777Mock. Here for easier decoding
event BeforeTokenTransfer();
bool private _shouldRevertSend;
bool private _shouldRevertReceive;
IERC1820Registry public _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 public constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender");
bytes32 public constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external override {
if (_shouldRevertSend) {
revert();
}
IERC777 token = IERC777(_msgSender());
uint256 fromBalance = token.balanceOf(from);
// when called due to burn, to will be the zero address, which will have a balance of 0
uint256 toBalance = token.balanceOf(to);
emit TokensToSendCalled(
operator,
from,
to,
amount,
userData,
operatorData,
address(token),
fromBalance,
toBalance
);
}
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external override {
if (_shouldRevertReceive) {
revert();
}
IERC777 token = IERC777(_msgSender());
uint256 fromBalance = token.balanceOf(from);
// when called due to burn, to will be the zero address, which will have a balance of 0
uint256 toBalance = token.balanceOf(to);
emit TokensReceivedCalled(
operator,
from,
to,
amount,
userData,
operatorData,
address(token),
fromBalance,
toBalance
);
}
function senderFor(address account) public {
_registerInterfaceForAddress(_TOKENS_SENDER_INTERFACE_HASH, account);
address self = address(this);
if (account == self) {
registerSender(self);
}
}
function registerSender(address sender) public {
_erc1820.setInterfaceImplementer(address(this), _TOKENS_SENDER_INTERFACE_HASH, sender);
}
function recipientFor(address account) public {
_registerInterfaceForAddress(_TOKENS_RECIPIENT_INTERFACE_HASH, account);
address self = address(this);
if (account == self) {
registerRecipient(self);
}
}
function registerRecipient(address recipient) public {
_erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, recipient);
}
function setShouldRevertSend(bool shouldRevert) public {
_shouldRevertSend = shouldRevert;
}
function setShouldRevertReceive(bool shouldRevert) public {
_shouldRevertReceive = shouldRevert;
}
function send(
IERC777 token,
address to,
uint256 amount,
bytes memory data
) public {
// This is 777's send function, not the Solidity send function
token.send(to, amount, data); // solhint-disable-line check-send-result
}
function burn(
IERC777 token,
uint256 amount,
bytes memory data
) public {
token.burn(amount, data);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC1820Implementer.sol)
pragma solidity ^0.8.0;
import "IERC1820Implementer.sol";
/**
* @dev Implementation of the {IERC1820Implementer} interface.
*
* Contracts may inherit from this and call {_registerInterfaceForAddress} to
* declare their willingness to be implementers.
* {IERC1820Registry-setInterfaceImplementer} should then be called for the
* registration to be complete.
*/
contract ERC1820Implementer is IERC1820Implementer {
bytes32 private constant _ERC1820_ACCEPT_MAGIC = keccak256("ERC1820_ACCEPT_MAGIC");
mapping(bytes32 => mapping(address => bool)) private _supportedInterfaces;
/**
* @dev See {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account)
public
view
virtual
override
returns (bytes32)
{
return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00);
}
/**
* @dev Declares the contract as willing to be an implementer of
* `interfaceHash` for `account`.
*
* See {IERC1820Registry-setInterfaceImplementer} and
* {IERC1820Registry-interfaceHash}.
*/
function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual {
_supportedInterfaces[interfaceHash][account] = true;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Implementer.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for an ERC1820 implementer, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP].
* Used by contracts that will be registered as implementers in the
* {IERC1820Registry}.
*/
interface IERC1820Implementer {
/**
* @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract
* implements `interfaceHash` for `account`.
*
* See {IERC1820Registry-setInterfaceImplementer}.
*/
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "ABDKMath64x64.sol";
import "Strings.sol";
library ExternalFuncs {
// from here https://medium.com/coinmonks/math-in-solidity-part-4-compound-interest-512d9e13041b
/*
function pow (int128 x, uint n)
public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt (1);
while (n > 0) {
if (n % 2 == 1) {
r = ABDKMath64x64.mul (r, x);
n -= 1;
} else {
x = ABDKMath64x64.mul (x, x);
n /= 2;
}
}
}
*/
function compound(
uint256 principal,
uint256 ratio,
uint256 n
) public pure returns (uint256) {
return
ABDKMath64x64.mulu(
ABDKMath64x64.pow( //pow - original code
ABDKMath64x64.add(
ABDKMath64x64.fromUInt(1),
ABDKMath64x64.divu(ratio, 10**4)
), //(1+r), where r is allowed to be one hundredth of a percent, ie 5/100/100
n
), //(1+r)^n
principal
); //A_0 * (1+r)^n
}
function Today() public view returns (uint256) {
return block.timestamp / 1 days;
}
function isStakeSizeOk(uint256 amount, uint256 decimals)
public
pure
returns (bool)
{
return
amount == 1000 * 10**decimals ||
amount == 3000 * 10**decimals ||
amount == 5000 * 10**decimals ||
amount == 10000 * 10**decimals ||
amount == 20000 * 10**decimals ||
amount == 50000 * 10**decimals ||
amount == 100000 * 10**decimals ||
amount == 250000 * 10**decimals ||
amount >= 1000000 * 10**decimals;
}
function getErrorMsg(string memory text, uint256 value)
public
pure
returns (string memory)
{
string memory _msg = string(
abi.encodePacked(text, Strings.toString(value))
);
return _msg;
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt(int256 x) internal pure returns (int128) {
unchecked {
require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt(int128 x) internal pure returns (int64) {
unchecked {
return int64(x >> 64);
}
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
unchecked {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(int256(x << 64));
}
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt(int128 x) internal pure returns (uint64) {
unchecked {
require(x >= 0);
return uint64(uint128(x >> 64));
}
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128(int256 x) internal pure returns (int128) {
unchecked {
int256 result = x >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128(int128 x) internal pure returns (int256) {
unchecked {
return int256(x) << 64;
}
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) + y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) - y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli(int128 x, int256 y) internal pure returns (int256) {
unchecked {
if (x == MIN_64x64) {
require(
y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000
);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu(x, uint256(y));
if (negativeResult) {
require(
absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(absoluteResult); // We rely on overflow behavior here
} else {
require(
absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(absoluteResult);
}
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu(int128 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) return 0;
require(x >= 0);
uint256 lo = (uint256(int256(x)) *
(y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(int256(x)) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(
hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -
lo
);
return hi + lo;
}
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div(int128 x, int128 y) internal pure returns (int128) {
unchecked {
require(y != 0);
int256 result = (int256(x) << 64) / y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi(int256 x, int256 y) internal pure returns (int128) {
unchecked {
require(y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu(uint256(x), uint256(y));
if (negativeResult) {
require(absoluteResult <= 0x80000000000000000000000000000000);
return -int128(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(absoluteResult); // We rely on overflow behavior here
}
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu(uint256 x, uint256 y) internal pure returns (int128) {
unchecked {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg(int128 x) internal pure returns (int128) {
unchecked {
require(x != MIN_64x64);
return -x;
}
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs(int128 x) internal pure returns (int128) {
unchecked {
require(x != MIN_64x64);
return x < 0 ? -x : x;
}
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv(int128 x) internal pure returns (int128) {
unchecked {
require(x != 0);
int256 result = int256(0x100000000000000000000000000000000) / x;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg(int128 x, int128 y) internal pure returns (int128) {
unchecked {
return int128((int256(x) + int256(y)) >> 1);
}
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 m = int256(x) * int256(y);
require(m >= 0);
require(
m <
0x4000000000000000000000000000000000000000000000000000000000000000
);
return int128(sqrtu(uint256(m)));
}
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow(int128 x, uint256 y) internal pure returns (int128) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128(x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x2 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x4 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x8 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) {
absX <<= 32;
absXShift -= 32;
}
if (absX < 0x10000000000000000000000000000) {
absX <<= 16;
absXShift -= 16;
}
if (absX < 0x1000000000000000000000000000000) {
absX <<= 8;
absXShift -= 8;
}
if (absX < 0x10000000000000000000000000000000) {
absX <<= 4;
absXShift -= 4;
}
if (absX < 0x40000000000000000000000000000000) {
absX <<= 2;
absXShift -= 2;
}
if (absX < 0x80000000000000000000000000000000) {
absX <<= 1;
absXShift -= 1;
}
uint256 resultShift = 0;
while (y != 0) {
require(absXShift < 64);
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = (absX * absX) >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require(resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256(absResult) : int256(absResult);
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt(int128 x) internal pure returns (int128) {
unchecked {
require(x >= 0);
return int128(sqrtu(uint256(int256(x)) << 64));
}
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2(int128 x) internal pure returns (int128) {
unchecked {
require(x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256(int256(x)) << uint256(127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln(int128 x) internal pure returns (int128) {
unchecked {
require(x > 0);
return
int128(
int256(
(uint256(int256(log_2(x))) *
0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128
)
);
}
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2(int128 x) internal pure returns (int128) {
unchecked {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (x & 0x4000000000000000 > 0)
result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (x & 0x2000000000000000 > 0)
result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (x & 0x1000000000000000 > 0)
result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (x & 0x800000000000000 > 0)
result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (x & 0x400000000000000 > 0)
result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (x & 0x200000000000000 > 0)
result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (x & 0x100000000000000 > 0)
result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (x & 0x80000000000000 > 0)
result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (x & 0x40000000000000 > 0)
result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (x & 0x20000000000000 > 0)
result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (x & 0x10000000000000 > 0)
result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (x & 0x8000000000000 > 0)
result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (x & 0x4000000000000 > 0)
result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (x & 0x2000000000000 > 0)
result = (result * 0x1000162E525EE054754457D5995292026) >> 128;
if (x & 0x1000000000000 > 0)
result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (x & 0x800000000000 > 0)
result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (x & 0x400000000000 > 0)
result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (x & 0x200000000000 > 0)
result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (x & 0x100000000000 > 0)
result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (x & 0x80000000000 > 0)
result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (x & 0x40000000000 > 0)
result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (x & 0x20000000000 > 0)
result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (x & 0x10000000000 > 0)
result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (x & 0x8000000000 > 0)
result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (x & 0x4000000000 > 0)
result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (x & 0x2000000000 > 0)
result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (x & 0x1000000000 > 0)
result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (x & 0x800000000 > 0)
result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (x & 0x400000000 > 0)
result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (x & 0x200000000 > 0)
result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (x & 0x100000000 > 0)
result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (x & 0x80000000 > 0)
result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (x & 0x40000000 > 0)
result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (x & 0x20000000 > 0)
result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (x & 0x10000000 > 0)
result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (x & 0x8000000 > 0)
result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (x & 0x4000000 > 0)
result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (x & 0x2000000 > 0)
result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (x & 0x1000000 > 0)
result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (x & 0x800000 > 0)
result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (x & 0x400000 > 0)
result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (x & 0x200000 > 0)
result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (x & 0x100000 > 0)
result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (x & 0x80000 > 0)
result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (x & 0x40000 > 0)
result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (x & 0x20000 > 0)
result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (x & 0x10000 > 0)
result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (x & 0x8000 > 0)
result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (x & 0x4000 > 0)
result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (x & 0x2000 > 0)
result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (x & 0x1000 > 0)
result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (x & 0x800 > 0)
result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (x & 0x400 > 0)
result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (x & 0x200 > 0)
result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (x & 0x100 > 0)
result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (x & 0x80 > 0)
result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (x & 0x40 > 0)
result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (x & 0x20 > 0)
result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (x & 0x10 > 0)
result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (x & 0x8 > 0)
result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (x & 0x4 > 0)
result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (x & 0x2 > 0)
result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (x & 0x1 > 0)
result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;
result >>= uint256(int256(63 - (x >> 64)));
require(result <= uint256(int256(MAX_64x64)));
return int128(int256(result));
}
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp(int128 x) internal pure returns (int128) {
unchecked {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return
exp_2(
int128(
(int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128
)
);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu(uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) private pure returns (uint128) {
unchecked {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128(r < r1 ? r : r1);
}
}
}
} | We rely on overflow behavior here
| y = -y; | 154,111 | [
1,
3218,
21187,
603,
9391,
6885,
2674,
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,
10792,
677,
273,
300,
93,
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
] |
pragma solidity 0.4.25;
/*
▒ █ ▀ ▀ ▀ █ ▒ █ ▀ ▀ █ ░ █ ▀ ▀ █ ▒ █ ▀ ▀ █ ▒ █ ░ ▄ ▀ ▒ █ ░ ░ ░ ▒ █ ▀ ▀ ▀
░ ▀ ▀ ▀ ▄ ▄ ▒ █ ▄ ▄ █ ▒ █ ▄ ▄ █ ▒ █ ▄ ▄ ▀ ▒ █ ▀ ▄ ░ ▒ █ ░ ░ ░ ▒ █ ▀ ▀ ▀
▒ █ ▄ ▄ ▄ █ ▒ █ ░ ░ ░ ▒ █ ░ ▒ █ ▒ █ ░ ▒ █ ▒ █ ░ ▒ █ ▒ █ ▄ ▄ █ ▒ █ ▄ ▄ ▄
░ █ ▀ ▀ █ ▀ █ ▀ ▒ █ ▀ ▀ █ ▒ █ ▀ ▀ ▄ ▒ █ ▀ ▀ █ ▒ █ ▀ ▀ ▀ █ ▒ █ ▀ ▀ █
▒ █ ▄ ▄ █ ▒ █ ░ ▒ █ ▄ ▄ ▀ ▒ █ ░ ▒ █ ▒ █ ▄ ▄ ▀ ▒ █ ░ ░ ▒ █ ▒ █ ▄ ▄ █
▒ █ ░ ▒ █ ▄ █ ▄ ▒ █ ░ ▒ █ ▒ █ ▄ ▄ ▀ ▒ █ ░ ▒ █ ▒ █ ▄ ▄ ▄ █ ▒ █ ░ ░ ░
https://sparklemobile.io/
Contract can be paused and resumed, but that could also load/reload for later dates*
NOTES:
,_, _ In order to "claim tokens" you must first add our token contract address "0x4b7aD3a56810032782Afce12d7d27122bDb96efF"
[0,0]
|)__)
-”-”-
,_, _ Did you hear FREE Sparkle!
[0,0]
|)__)
-”-”- 1) Opposed to setting max number of airdrop winners I changed it to just give out the default airdrod reward to any
added address to the airdrop list(see note 3 below). When the tokens run out then the contract will not honor any
airdrop awards but can still be run and tokens added to continue using the contract for other giveaways.
,_, _ Follow us on Twitter!
[0,0]
|)__)
-”-”- 2) Added functions to allow adding address(es) with a different token reward than the standard 30 for those cases
where some addresses we may want them to have more of an airdrop than the default
,_, _ Like us on Facebook
[0,0]
|)__)
-”-”- 3) I tried to make sure that the general cases of people senting eth to the contract is reverted and not accepted
however I am not positive this can stop someone that is determined. With that said I did not add anything to withdraw
that potential eth so it would be stuck in this contract if someone happens to send the contract ETH...
,_, _ Join our Telegram and Discord!
[0,0]
|)__)
-”-”- 4)Contract was built with the intention of security in mind, all contracts are built with OpenZeppelin 2.0 latest release
https://github.com/OpenZeppelin/openzeppelin-solidity/releases
*/
contract Ownable {
address public ownerField;
constructor() public {
ownerField = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == ownerField, "Calling address not an owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
ownerField = newOwner;
}
function owner() public view returns(address) {
return ownerField;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
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
);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer 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) {
_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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_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 != 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 != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
contract Pausable is Ownable {
bool public paused;
modifier ifNotPaused {
require(!paused, "Contract is paused");
_;
}
modifier ifPaused {
require(paused, "Contract is not paused");
_;
}
// Called by the owner on emergency, triggers paused state
function pause() external onlyOwner {
paused = true;
}
// Called by the owner on end of emergency, returns to normal state
function resume() external onlyOwner ifPaused {
paused = false;
}
}
contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
}
contract SparkleAirDrop is AirDropWinners {
using SafeMath for uint256;
address initTokenContractAddress = 0x4b7aD3a56810032782Afce12d7d27122bDb96efF;
constructor()
AirDropWinners(initTokenContractAddress)
public
{}
} | * @dev Multiplies two numbers, reverts on overflow./ 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 | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
| 986,588 | [
1,
5002,
5259,
2795,
5600,
16,
15226,
87,
603,
9391,
18,
19,
31849,
14850,
30,
333,
353,
19315,
7294,
2353,
29468,
296,
69,
11,
486,
3832,
3634,
16,
1496,
326,
27641,
7216,
353,
13557,
309,
296,
70,
11,
353,
2546,
18432,
18,
2164,
30,
2333,
30,
6662,
18,
832,
19,
3678,
62,
881,
84,
292,
267,
19,
3190,
94,
881,
84,
292,
267,
17,
30205,
560,
19,
13469,
19,
25,
3787,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
2583,
12,
71,
342,
279,
422,
324,
1769,
203,
565,
327,
276,
31,
203,
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
] |
./partial_match/3/0xc64C4B475C4ee0b30A4E0D3F875A4541e6d480a1/sources/stakingContract.sol | get total rewards withdrawn by poolId | function getTotalRewardsWithdrawnInPool(uint256 _poolId) public constant returns ( uint256 _totalWithdrawn) {
return stakingPool[_poolId].rewardsWithdrawn;
}
| 5,125,855 | [
1,
588,
2078,
283,
6397,
598,
9446,
82,
635,
2845,
548,
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,
12831,
17631,
14727,
1190,
9446,
82,
382,
2864,
12,
11890,
5034,
389,
6011,
548,
13,
1071,
5381,
1135,
261,
2254,
5034,
389,
4963,
1190,
9446,
82,
13,
288,
203,
3639,
327,
384,
6159,
2864,
63,
67,
6011,
548,
8009,
266,
6397,
1190,
9446,
82,
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
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract Structs {
/*
* State variable =>
* scope of variable is global
* (can be used in the whole program)
*/
uint public myUint = 1; // uint => unsigned integer (positive values)
address public myAddress = 0x4C501d78c6Bf497d276dcB2D6aDD66B351CcDb85; // ethereum address
string public myString = "Hello World!";
/*
* Struct =>
* create custom data structures
*/
struct MyStruct {
address id;
uint amount;
}
MyStruct public myStruct = MyStruct(0x4C501d78c6Bf497d276dcB2D6aDD66B351CcDb85, 1);
/*
* local variable =>
* scope of variable is only inside the
* function
*/
function getValue() public pure returns(uint) {
uint value = 1;
return value;
}
}
| local variable => scope of variable is only inside the function/ | function getValue() public pure returns(uint) {
uint value = 1;
return value;
}
| 2,560,525 | [
1,
3729,
2190,
516,
2146,
434,
2190,
353,
1338,
4832,
326,
445,
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,
565,
445,
2366,
1435,
1071,
16618,
1135,
12,
11890,
13,
288,
203,
3639,
2254,
460,
273,
404,
31,
203,
3639,
327,
460,
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
] |
./partial_match/1/0x8Fc8f8269ebca376D046Ce292dC7eaC40c8D358A/sources/DFI.sol | * @dev DFI ERC20 token, including: - Referenced from OpenZeppelin v3.3 preset: presets/ERC20PresetMinterPauser.sol - with pauser role and pause functionality removed/ | contract DFI is Context, AccessControl, ERC20Burnable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
string private _backingAddress = "dZFYejknFdHMHNfHMNQAtwihzvq7DkzV49";
constructor() ERC20("DeFiChain Token", "DFI") {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupDecimals(8);
}
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "DFI: must have minter role to mint");
_mint(to, amount);
}
function backingAddress() public view returns (string memory) {
return _backingAddress;
}
function setBackingAddress(string memory backingAddress_) public virtual {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "DFI: must have admin role to set backing address");
_backingAddress = backingAddress_;
}
} | 3,701,682 | [
1,
40,
1653,
4232,
39,
3462,
1147,
16,
6508,
30,
225,
300,
6268,
72,
628,
3502,
62,
881,
84,
292,
267,
331,
23,
18,
23,
12313,
30,
24649,
19,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
18,
18281,
225,
300,
598,
6790,
1355,
2478,
471,
11722,
14176,
3723,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
463,
1653,
353,
1772,
16,
24349,
16,
4232,
39,
3462,
38,
321,
429,
288,
203,
565,
1731,
1578,
1071,
5381,
6989,
2560,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
6236,
2560,
67,
16256,
8863,
203,
565,
533,
3238,
389,
823,
310,
1887,
273,
315,
72,
62,
42,
61,
73,
78,
21112,
27263,
44,
49,
44,
50,
74,
44,
49,
50,
53,
861,
91,
7392,
94,
90,
85,
27,
40,
79,
94,
58,
7616,
14432,
203,
203,
203,
565,
3885,
1435,
4232,
39,
3462,
2932,
758,
42,
77,
3893,
3155,
3113,
315,
40,
1653,
7923,
288,
203,
3639,
389,
8401,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
389,
3576,
12021,
10663,
203,
3639,
389,
8401,
2996,
12,
6236,
2560,
67,
16256,
16,
389,
3576,
12021,
10663,
203,
3639,
389,
8401,
31809,
12,
28,
1769,
203,
565,
289,
203,
203,
565,
445,
312,
474,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
1071,
5024,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
6236,
2560,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
315,
40,
1653,
30,
1297,
1240,
1131,
387,
2478,
358,
312,
474,
8863,
203,
3639,
389,
81,
474,
12,
869,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
15394,
1887,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
823,
310,
1887,
31,
203,
565,
289,
203,
203,
565,
445,
444,
2711,
310,
1887,
12,
1080,
3778,
15394,
1887,
67,
13,
1071,
5024,
288,
203,
1377,
2583,
12,
5332,
2996,
12,
5280,
67,
15468,
67,
2
] |
./full_match/7672/0x04742440f3272232Dd46FCDb3e86A4c2961d5164/sources/contracts/libraries/Manageable.sol | * @dev Contract module which provides a basic access control mechanism, where there is an list of public managers who may be added or removed. 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 other contracts which have explicitly been added./ | abstract contract Manageable is Ownable2StepUpgradeable {
mapping(address => uint256) public managers;
error OnlyManagers();
error ManagerCannotBeZeroAddress();
pragma solidity ^0.8.18;
function addManager(address manager) external onlyOwner {
if (manager == address(0)) {
revert ManagerCannotBeZeroAddress();
}
managers[manager] = block.number;
}
function addManager(address manager) external onlyOwner {
if (manager == address(0)) {
revert ManagerCannotBeZeroAddress();
}
managers[manager] = block.number;
}
function removeManager(address manager) external onlyOwner {
delete managers[manager];
}
modifier onlyManager() {
if (managers[msg.sender] == 0) {
revert OnlyManagers();
}
_;
}
modifier onlyManager() {
if (managers[msg.sender] == 0) {
revert OnlyManagers();
}
_;
}
uint256[49] private __gap;
}
| 16,296,176 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
666,
434,
1071,
21103,
10354,
2026,
506,
3096,
578,
3723,
18,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
1318,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
1308,
20092,
1492,
1240,
8122,
2118,
3096,
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,
17801,
6835,
24247,
429,
353,
14223,
6914,
22,
4160,
10784,
429,
288,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
21103,
31,
203,
203,
565,
555,
5098,
17570,
5621,
203,
565,
555,
8558,
4515,
1919,
7170,
1887,
5621,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2643,
31,
203,
565,
445,
527,
1318,
12,
2867,
3301,
13,
3903,
1338,
5541,
288,
203,
3639,
309,
261,
4181,
422,
1758,
12,
20,
3719,
288,
203,
5411,
15226,
8558,
4515,
1919,
7170,
1887,
5621,
203,
3639,
289,
203,
3639,
21103,
63,
4181,
65,
273,
1203,
18,
2696,
31,
203,
565,
289,
203,
203,
565,
445,
527,
1318,
12,
2867,
3301,
13,
3903,
1338,
5541,
288,
203,
3639,
309,
261,
4181,
422,
1758,
12,
20,
3719,
288,
203,
5411,
15226,
8558,
4515,
1919,
7170,
1887,
5621,
203,
3639,
289,
203,
3639,
21103,
63,
4181,
65,
273,
1203,
18,
2696,
31,
203,
565,
289,
203,
203,
565,
445,
1206,
1318,
12,
2867,
3301,
13,
3903,
1338,
5541,
288,
203,
3639,
1430,
21103,
63,
4181,
15533,
203,
565,
289,
203,
203,
565,
9606,
1338,
1318,
1435,
288,
203,
3639,
309,
261,
29757,
63,
3576,
18,
15330,
65,
422,
374,
13,
288,
203,
5411,
15226,
5098,
17570,
5621,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
1318,
1435,
288,
203,
3639,
309,
261,
29757,
63,
3576,
18,
15330,
65,
422,
374,
13,
288,
203,
5411,
15226,
5098,
17570,
5621,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
2
] |
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract TokenSwap is Ownable {
using SafeMath for uint256;
IERC20 private _fromToken;
IERC20 private _toToken;
uint256 private _rate;
event Swap(address indexed sender, uint256 indexed fromTokenAmount, uint256 indexed toTokenAmount);
event Deactivate(uint256 indexed amount);
constructor(
address fromToken,
address toToken,
uint256 rate
) Ownable() public {
require(fromToken != address(0x0) && toToken != address(0x0), "token address can not be 0.");
require(rate > 0, "swap rate can not be 0.");
_fromToken = IERC20(fromToken);
_toToken = IERC20(toToken);
_rate = rate;
}
function swap() external returns (bool) {
uint256 allowance = _fromToken.allowance(msg.sender, address(this));
require(allowance > 0, "sender need to approve token to swap contract.");
if (_fromToken.transferFrom(msg.sender, address(0x0), allowance)) {
// It only works correctly when the rate is 1000.
uint256 swappedValue = allowance.add(999);
swappedValue = swappedValue.div(_rate);
require(_toToken.transferFrom(Ownable.owner(), msg.sender, swappedValue));
emit Swap(msg.sender, allowance, swappedValue);
}
return true;
}
function deactivate() external onlyOwner {
uint256 reserve = _fromToken.balanceOf(address(this));
require(_fromToken.transfer(address(0x0), reserve));
emit Deactivate(reserve);
}
} | It only works correctly when the rate is 1000. | function swap() external returns (bool) {
uint256 allowance = _fromToken.allowance(msg.sender, address(this));
require(allowance > 0, "sender need to approve token to swap contract.");
if (_fromToken.transferFrom(msg.sender, address(0x0), allowance)) {
uint256 swappedValue = allowance.add(999);
swappedValue = swappedValue.div(_rate);
require(_toToken.transferFrom(Ownable.owner(), msg.sender, swappedValue));
emit Swap(msg.sender, allowance, swappedValue);
}
return true;
}
| 12,585,809 | [
1,
7193,
1338,
6330,
8783,
1347,
326,
4993,
353,
4336,
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
] | [
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,
7720,
1435,
3903,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
1699,
1359,
273,
389,
2080,
1345,
18,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
10019,
203,
3639,
2583,
12,
5965,
1359,
405,
374,
16,
315,
15330,
1608,
358,
6617,
537,
1147,
358,
7720,
6835,
1199,
1769,
203,
203,
3639,
309,
261,
67,
2080,
1345,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
20,
92,
20,
3631,
1699,
1359,
3719,
288,
203,
5411,
2254,
5034,
7720,
1845,
620,
273,
1699,
1359,
18,
1289,
12,
11984,
1769,
203,
5411,
7720,
1845,
620,
273,
7720,
1845,
620,
18,
2892,
24899,
5141,
1769,
203,
203,
5411,
2583,
24899,
869,
1345,
18,
13866,
1265,
12,
5460,
429,
18,
8443,
9334,
1234,
18,
15330,
16,
7720,
1845,
620,
10019,
203,
203,
5411,
3626,
12738,
12,
3576,
18,
15330,
16,
1699,
1359,
16,
7720,
1845,
620,
1769,
203,
3639,
289,
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
] |
pragma solidity 0.8.4;
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/access/Ownable.sol";
import "./YourToken.sol";
contract Vendor is Ownable {
event BuyTokens(address buyer, uint256 amountOfETH, uint256 amountOfTokens);
uint256 public constant tokensPerEth = 100;
YourToken public yourToken;
constructor(address tokenAddress) {
yourToken = YourToken(tokenAddress);
}
// ToDo: create a payable buyTokens() function:
function buyTokens() public payable {
uint256 amount = msg.value * tokensPerEth;
yourToken.transfer(msg.sender, amount);
emit BuyTokens(msg.sender, msg.value, amount);
}
// ToDo: create a withdraw() function that lets the owner withdraw ETH
function withdraw() external {
(bool success, ) = owner().call{value: address(this).balance}('');
require(success, 'ERROR at withdrawing');
}
// ToDo: create a sellTokens() function:
function sellTokens(uint256 amount) external {
yourToken.transferFrom(msg.sender, address(this), amount);
(bool payedSeller, ) = msg.sender.call{value: amount / tokensPerEth}('');
require(payedSeller, 'Unable to pay seller');
}
}
| ToDo: create a sellTokens() function: | function sellTokens(uint256 amount) external {
yourToken.transferFrom(msg.sender, address(this), amount);
require(payedSeller, 'Unable to pay seller');
}
| 12,835,987 | [
1,
774,
3244,
30,
752,
279,
357,
80,
5157,
1435,
445,
30,
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,
225,
445,
357,
80,
5157,
12,
11890,
5034,
3844,
13,
3903,
288,
203,
565,
3433,
1345,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
203,
565,
2583,
12,
10239,
329,
22050,
16,
296,
3370,
358,
8843,
29804,
8284,
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
] |
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol | * @dev Interface of the ERC20 standard as defined in the EIP./ | interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, 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 from, address to, uint256 amount) external returns (bool);
}
| 8,818,716 | [
1,
1358,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
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
] | [
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,
1560,
467,
654,
39,
3462,
288,
203,
3639,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
3639,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
203,
3639,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
3639,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
3639,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
3639,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
3639,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
3639,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-07-28
*/
pragma solidity 0.6.0;
/**
* @title Offering contract
* @dev Offering + take order + NEST allocation
*/
contract Nest_3_OfferMain {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
struct Nest_3_OfferPriceData {
// The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress())
address owner; // Offering owner
bool deviate; // Whether it deviates
address tokenAddress; // The erc20 contract address of the target offer token
uint256 ethAmount; // The ETH amount in the offer list
uint256 tokenAmount; // The token amount in the offer list
uint256 dealEthAmount; // The remaining number of tradable ETH
uint256 dealTokenAmount; // The remaining number of tradable tokens
uint256 blockNum; // The block number where the offer is located
uint256 serviceCharge; // The fee for mining
// Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0
}
Nest_3_OfferPriceData [] _prices; // Array used to save offers
mapping(address => bool) _tokenAllow; // List of allowed mining token
Nest_3_VoteFactory _voteFactory; // Vote contract
Nest_3_OfferPrice _offerPrice; // Price contract
Nest_3_MiningContract _miningContract; // Mining contract
Nest_NodeAssignment _NNcontract; // NestNode contract
ERC20 _nestToken; // NestToken
Nest_3_Abonus _abonus; // Bonus pool
address _coderAddress; // Developer address
uint256 _miningETH = 10; // Offering mining fee ratio
uint256 _tranEth = 1; // Taker fee ratio
uint256 _tranAddition = 2; // Additional transaction multiple
uint256 _coderAmount = 5; // Developer ratio
uint256 _NNAmount = 15; // NestNode ratio
uint256 _leastEth = 10 ether; // Minimum offer of ETH
uint256 _offerSpan = 10 ether; // ETH Offering span
uint256 _deviate = 10; // Price deviation - 10%
uint256 _deviationFromScale = 10; // Deviation from asset scale
uint32 _blockLimit = 25; // Block interval upper limit
mapping(uint256 => uint256) _offerBlockEth; // Block offer fee
mapping(uint256 => uint256) _offerBlockMining; // Block mining amount
// Log offering contract, token address, number of eth, number of erc20, number of continuous blocks, number of fees
event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued, uint256 serviceCharge);
// Log transaction, transaction initiator, transaction token address, number of transaction token, token address, number of token, traded offering contract address, traded user address
event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner);
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave")));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment")));
_coderAddress = voteFactoryMap.checkAddress("nest.v3.coder");
require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed");
}
/**
* @dev Reset voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave")));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment")));
_coderAddress = voteFactoryMap.checkAddress("nest.v3.coder");
require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed");
}
/**
* @dev Offering mining
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 token amount
* @param erc20Address Offering erc20 token address
*/
function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
require(_tokenAllow[erc20Address], "Token not allow");
// Judge whether the price deviates
uint256 ethMining;
bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address);
if (isDeviate) {
require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale");
ethMining = _leastEth.mul(_miningETH).div(1000);
} else {
ethMining = ethAmount.mul(_miningETH).div(1000);
}
require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee");
uint256 subValue = msg.value.sub(ethAmount.add(ethMining));
if (subValue > 0) {
repayEth(address(msg.sender), subValue);
}
// Create an offer
createOffer(ethAmount, erc20Amount, erc20Address, ethMining, isDeviate);
// Transfer in offer asset - erc20 to this contract
ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount);
// Mining
uint256 miningAmount = _miningContract.oreDrawing();
_abonus.switchToEth.value(ethMining)(address(_nestToken));
if (miningAmount > 0) {
uint256 coder = miningAmount.mul(_coderAmount).div(100);
uint256 NN = miningAmount.mul(_NNAmount).div(100);
uint256 other = miningAmount.sub(coder).sub(NN);
_offerBlockMining[block.number] = other;
_NNcontract.bookKeeping(NN);
if (coder > 0) {
_nestToken.safeTransfer(_coderAddress, coder);
}
}
_offerBlockEth[block.number] = _offerBlockEth[block.number].add(ethMining);
}
/**
* @dev Create offer
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 amount
* @param erc20Address Offering erc20 address
* @param mining Offering mining fee (0 for takers)
* @param isDeviate Whether the current price chain deviates
*/
function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, uint256 mining, bool isDeviate) private {
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale");
require(ethAmount % _offerSpan == 0, "Non compliant asset span");
require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided");
require(erc20Amount > 0);
// Create offering contract
emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining);
_prices.push(Nest_3_OfferPriceData(
msg.sender,
isDeviate,
erc20Address,
ethAmount,
erc20Amount,
ethAmount,
erc20Amount,
block.number,
mining
));
// Record price
_offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender));
}
/**
* @dev Taker order - pay ETH and buy erc20
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate);
// Transfer in erc20 + offer asset to this contract
if (tokenAmount > tranTokenAmount) {
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount));
} else {
ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount));
}
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
_abonus.switchToEth.value(serviceCharge)(address(_nestToken));
}
}
/**
* @dev Taker order - pay erc20 and buy ETH
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate);
// Transfer in erc20 + offer asset to this contract
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount));
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
_abonus.switchToEth.value(serviceCharge)(address(_nestToken));
}
}
/**
* @dev Withdraw the assets, and settle the mining
* @param contractAddress The offer address to withdraw
*/
function turnOut(address contractAddress) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData storage offerPriceData = _prices[index];
require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error");
// Withdraw ETH
if (offerPriceData.ethAmount > 0) {
uint256 payEth = offerPriceData.ethAmount;
offerPriceData.ethAmount = 0;
repayEth(offerPriceData.owner, payEth);
}
// Withdraw erc20
if (offerPriceData.tokenAmount > 0) {
uint256 payErc = offerPriceData.tokenAmount;
offerPriceData.tokenAmount = 0;
ERC20(address(offerPriceData.tokenAddress)).safeTransfer(offerPriceData.owner, payErc);
}
// Mining settlement
if (offerPriceData.serviceCharge > 0) {
uint256 myMiningAmount = offerPriceData.serviceCharge.mul(_offerBlockMining[offerPriceData.blockNum]).div(_offerBlockEth[offerPriceData.blockNum]);
_nestToken.safeTransfer(offerPriceData.owner, myMiningAmount);
offerPriceData.serviceCharge = 0;
}
}
// Convert offer address into index in offer array
function toIndex(address contractAddress) public pure returns(uint256) {
return uint256(contractAddress);
}
// Convert index in offer array into offer address
function toAddress(uint256 index) public pure returns(address) {
return address(index);
}
// View contract state
function checkContractState(uint256 createBlock) public view returns (uint256) {
if (block.number.sub(createBlock) > _blockLimit) {
return 1;
}
return 0;
}
// Compare the order price
function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) {
(uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token);
if (frontEthValue == 0 || frontTokenValue == 0) {
return false;
}
uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue <= maxTokenAmount) {
uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue >= minTokenAmount) {
return false;
}
}
return true;
}
// Transfer ETH
function repayEth(address accountAddress, uint256 asset) private {
address payable addr = accountAddress.make_payable();
addr.transfer(asset);
}
// View the upper limit of the block interval
function checkBlockLimit() public view returns(uint32) {
return _blockLimit;
}
// View offering mining fee ratio
function checkMiningETH() public view returns (uint256) {
return _miningETH;
}
// View whether the token is allowed to mine
function checkTokenAllow(address token) public view returns(bool) {
return _tokenAllow[token];
}
// View additional transaction multiple
function checkTranAddition() public view returns(uint256) {
return _tranAddition;
}
// View the development allocation ratio
function checkCoderAmount() public view returns(uint256) {
return _coderAmount;
}
// View the NestNode allocation ratio
function checkNNAmount() public view returns(uint256) {
return _NNAmount;
}
// View the least offering ETH
function checkleastEth() public view returns(uint256) {
return _leastEth;
}
// View offering ETH span
function checkOfferSpan() public view returns(uint256) {
return _offerSpan;
}
// View the price deviation
function checkDeviate() public view returns(uint256){
return _deviate;
}
// View deviation from scale
function checkDeviationFromScale() public view returns(uint256) {
return _deviationFromScale;
}
// View block offer fee
function checkOfferBlockEth(uint256 blockNum) public view returns(uint256) {
return _offerBlockEth[blockNum];
}
// View taker order fee ratio
function checkTranEth() public view returns (uint256) {
return _tranEth;
}
// View block mining amount of user
function checkOfferBlockMining(uint256 blockNum) public view returns(uint256) {
return _offerBlockMining[blockNum];
}
// View offer mining amount
function checkOfferMining(uint256 blockNum, uint256 serviceCharge) public view returns (uint256) {
if (serviceCharge == 0) {
return 0;
} else {
return _offerBlockMining[blockNum].mul(serviceCharge).div(_offerBlockEth[blockNum]);
}
}
// Change offering mining fee ratio
function changeMiningETH(uint256 num) public onlyOwner {
_miningETH = num;
}
// Modify taker fee ratio
function changeTranEth(uint256 num) public onlyOwner {
_tranEth = num;
}
// Modify the upper limit of the block interval
function changeBlockLimit(uint32 num) public onlyOwner {
_blockLimit = num;
}
// Modify whether the token allows mining
function changeTokenAllow(address token, bool allow) public onlyOwner {
_tokenAllow[token] = allow;
}
// Modify additional transaction multiple
function changeTranAddition(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_tranAddition = num;
}
// Modify the initial allocation ratio
function changeInitialRatio(uint256 coderNum, uint256 NNNum) public onlyOwner {
require(coderNum.add(NNNum) <= 100, "User allocation ratio error");
_coderAmount = coderNum;
_NNAmount = NNNum;
}
// Modify the minimum offering ETH
function changeLeastEth(uint256 num) public onlyOwner {
require(num > 0);
_leastEth = num;
}
// Modify the offering ETH span
function changeOfferSpan(uint256 num) public onlyOwner {
require(num > 0);
_offerSpan = num;
}
// Modify the price deviation
function changekDeviate(uint256 num) public onlyOwner {
_deviate = num;
}
// Modify the deviation from scale
function changeDeviationFromScale(uint256 num) public onlyOwner {
_deviationFromScale = num;
}
/**
* Get the number of offers stored in the offer array
* @return The number of offers stored in the offer array
**/
function getPriceCount() view public returns (uint256) {
return _prices.length;
}
/**
* Get offer information according to the index
* @param priceIndex Offer index
* @return Offer information
**/
function getPrice(uint256 priceIndex) view public returns (string memory) {
// The buffer array used to generate the result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index);
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Search the contract address list of the target account (reverse order)
* @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address)
* @param count Maximum number of records to return
* @param maxFindCount The max index to search
* @param owner Target account address
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Calculate search interval i and end
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = toIndex(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// Loop search, write qualified records into buffer
while (count > 0 && i-- > end) {
Nest_3_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = writeOfferPriceData(i, price, buf, index);
}
}
// Generate result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Get the list of offers by page
* @param offset Skip the first offset records
* @param count Maximum number of records to return
* @param order Sort rules. 0 means reverse order, non-zero means positive order
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Find search interval i and end
uint256 i = 0;
uint256 end = 0;
if (order == 0) {
// Reverse order, in default
// Calculate search interval i and end
if (offset < _prices.length) {
i = _prices.length - offset;
}
if (count < i) {
end = i - count;
}
// Write records in the target interval into the buffer
while (i-- > end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
}
} else {
// Ascending order
// Calculate the search interval i and end
if (offset < _prices.length) {
i = offset;
} else {
i = _prices.length;
}
end = i + count;
if(end > _prices.length) {
end = _prices.length;
}
// Write the records in the target interval into the buffer
while (i < end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
++i;
}
}
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
// Write the offer data into the buffer and return the buffer index
function writeOfferPriceData(uint256 priceIndex, Nest_3_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) {
index = writeAddress(toAddress(priceIndex), buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.owner, buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.tokenAddress, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.ethAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.tokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealEthAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealTokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.blockNum, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.serviceCharge, buf, index);
buf[index++] = byte(uint8(44));
return index;
}
// Convert integer to string in decimal form and write it into the buffer, and return the buffer index
function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) {
uint256 i = index;
do {
buf[index++] = byte(uint8(iv % 10 +48));
iv /= 10;
} while (iv > 0);
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index
function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) {
uint256 iv = uint256(addr);
uint256 i = index + 40;
do {
uint256 w = iv % 16;
if(w < 10) {
buf[index++] = byte(uint8(w +48));
} else {
buf[index++] = byte(uint8(w +87));
}
iv /= 16;
} while (index < i);
i -= 40;
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Vote administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
}
// NestNode assignment contract
interface Nest_NodeAssignment {
function bookKeeping(uint256 amount) external;
}
// Mining pool logic
interface Nest_3_MiningContract {
// Offering mining
function oreDrawing() external returns (uint256);
}
// Voting contract
interface Nest_3_VoteFactory {
// Check address
function checkAddress(string calldata name) external view returns (address contractAddress);
// Check whether administrator
function checkOwners(address man) external view returns (bool);
}
// Price contract
interface Nest_3_OfferPrice {
function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) external;
function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external;
function updateAndCheckPricePrivate(address tokenAddress) external view returns(uint256 ethAmount, uint256 erc20Amount);
}
// Bonus pool contract
interface Nest_3_Abonus {
function switchToEth(address token) external payable;
}
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;
}
}
library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
return address(uint160(x));
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 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(ERC20 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(ERC20 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(ERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ERC20 {
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);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
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");
}
} | Additional transaction multiple
| uint256 _tranAddition = 2; | 5,361,424 | [
1,
10552,
2492,
3229,
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,
0
] | [
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,
0
] | [
1,
565,
2254,
5034,
389,
13171,
30296,
273,
576,
31,
21821,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol";
import "@openzeppelin/contracts/interfaces/IERC721Receiver.sol";
import "hardhat/console.sol";
//ERC721 is already ERC16 so no need to inherit twice
contract Citadel is IERC721, IERC721Metadata{
// _earlyAccessHolders - external NFT holder for early mint
//TODO _cityRoot - ?
constructor(bytes32 _cityRoot){
supportedInterfaces[0x80ac58cd] = true; //ERC721
supportedInterfaces[0x5b5e139f] = true; //ERC721Metadata
// supportedInterfaces[0x780e9d63] = true; //ERC721Enumerable
supportedInterfaces[0x01ffc9a7] = true; //ERC165
owner = msg.sender;
cityRoot = _cityRoot;
}
address public owner;
//////===721 Implementation
mapping(address => uint256) internal balances;
mapping (uint256 => address) internal allowance;
mapping (address => mapping (address => bool)) internal authorised;
uint16[] tokenIndexToCity; //Array of all tokens [cityId,cityId,...]
mapping(uint256 => address) owners; //Mapping of owners
// keep owners mapping
// use tokenIndexToCity for isValidToken
// METADATA VARS
string private __name = "Citadel NFT game";
string private __symbol = "CITADEL";
// bytes private __uriBase = bytes("https://gateway.pinata.cloud/ipfs/QmUwPH9PmTQrT67M633AJRXACsecmRTihf4DUbJZb9y83M/");
bytes private __uriBase = bytes("https://media.istockphoto.com/vectors/castle-tower-vector-id1003186156?k=20&m=1003186156&s=612x612&w=0&h=4BE1Vx3Rmj933gspqShngkSnfYWOOE6H88kV5edZIRo=");
bytes private __uriSuffix = bytes("");
// bytes private __uriSuffix = bytes(".json");
// Game vars
//cities on the map
uint constant MAX_CITIES = 100; //from table
int16 constant MAP_WIDTH = 1000; //map units
int16 constant MAP_HEIGHT = 700; //map units
int16 constant BASE_BLAST_RADIUS = 50; //map units
uint constant MINT_COST = 0.04 ether; //it's in BNB but here 'ether' is used for 1e18
uint constant MINT_PERCENT_WINNER = 50;
uint constant MINT_PERCENT_CALLER = 25;
uint constant MINT_PERCENT_CREATOR = 25;
uint constant REINFORCE_PERCENT_WINNER = 90;
uint constant REINFORCE_PERCENT_CREATOR = 10;
// uint constant IMPACT_BLOCK_INTERVAL = 600; //BSC creates a block every 3s, so every 30 min means 30*60/3 = 600
uint constant IMPACT_BLOCK_INTERVAL = 1; //BSC creates a block every 3s, so every 30 min means 30*60/3 = 600
mapping(uint16 => uint) public cityToToken;
mapping(uint16 => int16[2]) coordinates;
bytes32 cityRoot;
event Inhabit(uint16 indexed _cityId, uint256 indexed _tokenId);
event Reinforce(uint256 indexed _tokenId);
event Impact(uint256 indexed _tokenId);
mapping(uint => bytes32) structuralData;
function getStructuralData(uint _tokenId) public view returns (uint8 reinforcement, uint8 damage, bytes32 lastImpact){
bytes32 _data = structuralData[_tokenId];
reinforcement = uint8(uint(((_data << 248) >> 248)));
damage = uint8(uint(((_data << 240) >> 240) >> 8));
lastImpact = (_data >> 16);
return (reinforcement, damage, lastImpact);
}
function setStructuralData(uint _tokenId, uint8 reinforcement, uint8 damage, bytes32 lastImpact) internal{
bytes32 _reinforcement = bytes32(uint(reinforcement));
bytes32 _damage = bytes32(uint(damage)) << 8;
bytes32 _lastImpact = encodeImpact(lastImpact) << 16;
structuralData[_tokenId] = _reinforcement ^ _damage ^ _lastImpact;
}
function encodeImpact(bytes32 _impact) internal pure returns(bytes32){
return (_impact << 16) >> 16;
}
uint public reinforcements;
uint public destroyed;
uint public evacuatedFunds;
uint ownerWithdrawn;
bool winnerWithdrawn;
function tokenToCity(uint _tokenId) public view returns(uint16){
return tokenIndexToCity[_tokenId - 1];
}
uint public startTime;
uint SALE_TIME = 7 days;
uint EARLY_ACCESS_TIME = 1 days;
function startPreSiege() public{
require(msg.sender == owner,"owner");
require(startTime == 0,"started");
startTime = block.timestamp;
}
enum Stage {Initial,PreSiege,Siege,PostSiege}
function stage() public view returns(Stage){
if(startTime == 0){
return Stage.Initial;
}else if(block.timestamp < startTime + SALE_TIME && tokenIndexToCity.length < MAX_CITIES){
return Stage.PreSiege;
}else if(destroyed < tokenIndexToCity.length - 1){
return Stage.Siege;
}else{
return Stage.PostSiege;
}
}
// mint the NFT
function inhabit(uint16 _cityId, int16[2] calldata _coordinates, bytes32[] memory proof) public payable{
require(stage() == Stage.PreSiege,"stage");
if(block.timestamp < startTime + EARLY_ACCESS_TIME){
//First day is insiders list
// require(IERC721(earlyAccessHolders).balanceOf(msg.sender) > 0,"early");
}
bytes32 leaf = keccak256(abi.encodePacked(_cityId,_coordinates[0],_coordinates[1]));
require(MerkleProof.verify(proof, cityRoot, leaf),"proof");
require(cityToToken[_cityId] == 0 && coordinates[_cityId][0] == 0 && coordinates[_cityId][1] == 0,"inhabited");
require(
_coordinates[0] >= 0 &&
_coordinates[0] <= MAP_WIDTH &&
_coordinates[1] >= 0 &&
_coordinates[1] <= MAP_HEIGHT,
"off map"
); //Not strictly necessary but proves the whitelist hasnt been fucked with
console.log("msg.value", msg.value);
require(msg.value == MINT_COST,"cost");
coordinates[_cityId] = _coordinates;
tokenIndexToCity.push(_cityId);
uint _tokenId = tokenIndexToCity.length;
balances[msg.sender]++;
owners[_tokenId] = msg.sender;
cityToToken[_cityId] = _tokenId;
emit Inhabit(_cityId, _tokenId);
emit Transfer(address(0),msg.sender,_tokenId);
}
function isUninhabited(uint16 _cityId) public view returns(bool){
return coordinates[_cityId][0] == 0 && coordinates[_cityId][1] == 0;
}
function reinforce(uint _tokenId) public payable{
Stage _stage = stage();
require(_stage == Stage.PreSiege || _stage == Stage.Siege,"stage");
require(ownerOf(_tokenId) == msg.sender,"owner");
//Covered by ownerOf
// require(isValidToken(_tokenId),"invalid");
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
if(_stage == Stage.Siege){
require(!checkVulnerable(_tokenId,_lastImpact),"vulnerable");
}
// covered by isValidToken
//require(_damage <= _reinforcement,"eliminated" );
require(msg.value == (2 ** _reinforcement) * MINT_COST,"cost");
setStructuralData(_tokenId,_reinforcement+1,_damage,_lastImpact);
reinforcements += msg.value - (MINT_COST * MINT_PERCENT_CALLER / 100);
emit Reinforce(_tokenId);
}
function evacuate(uint _tokenId) public{
Stage _stage = stage();
require(_stage == Stage.PreSiege || _stage == Stage.Siege,"stage");
require(ownerOf(_tokenId) == msg.sender,"owner");
// covered by isValidToken in ownerOf
// require(_damage <= _reinforcement,"eliminated" );
if(_stage == Stage.Siege){
require(!isVulnerable(_tokenId),"vulnerable");
}
uint cityCount = tokenIndexToCity.length;
uint fromPool =
//Winner fee from mints less evacuated funds
((MINT_COST * cityCount * MINT_PERCENT_WINNER / 100 - evacuatedFunds)
//Divided by remaining tokens
/ totalSupply())
//Divided by two
/ 2;
//Also give them the admin fee
uint toWithdraw = fromPool + getEvacuationRebate(_tokenId);
balances[owners[_tokenId]]--;
delete cityToToken[tokenToCity(_tokenId)];
destroyed++;
//Doesnt' include admin fees in evacedFunds
evacuatedFunds += fromPool;
emit Transfer(owners[_tokenId],address(0),_tokenId);
payable(msg.sender).send(
toWithdraw
);
}
function getEvacuationRebate(uint _tokenId) public view returns(uint) {
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
_lastImpact;
return MINT_COST * (1 + _reinforcement - _damage) * MINT_PERCENT_CALLER / 100;
}
function confirmHit(uint _tokenId) public{
require(stage() == Stage.Siege,"stage");
require(isValidToken(_tokenId),"invalid");
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
// covered by isValidToken
// require(_damage <= _reinforcement,"eliminated" );
require(checkVulnerable(_tokenId,_lastImpact),"vulnerable");
(int64[2] memory _coordinates, int64 _radius, bytes32 _impactId) = currentImpact();
_coordinates;_radius;
_impactId = encodeImpact(_impactId);
emit Impact(_tokenId);
if(_damage < _reinforcement){
_damage++;
setStructuralData(_tokenId,_reinforcement,_damage,_impactId);
}else{
balances[owners[_tokenId]]--;
delete cityToToken[tokenToCity(_tokenId)];
destroyed++;
emit Transfer(owners[_tokenId],address(0),_tokenId);
}
payable(msg.sender).send(MINT_COST * MINT_PERCENT_CALLER / 100);
}
function winnerWithdraw(uint _winnerTokenId) public{
require(stage() == Stage.PostSiege,"stage");
require(isValidToken(_winnerTokenId),"invalid");
// Implicitly makes sure its the right token since all others don't exist
require(msg.sender == ownerOf(_winnerTokenId),"ownerOf");
require(!winnerWithdrawn,"withdrawn");
winnerWithdrawn = true;
uint toWithdraw = winnerPrize(_winnerTokenId);
if(toWithdraw > address(this).balance){
//Catch rounding errors
toWithdraw = address(this).balance;
}
payable(msg.sender).send(toWithdraw);
}
function ownerWithdraw() public{
require(msg.sender == owner,"owner");
uint cityCount = tokenIndexToCity.length;
// Dev and creator portion of all mint fees collected
uint toWithdraw = MINT_COST * cityCount * (MINT_PERCENT_CREATOR) / 100
//plus reinforcement for creator
+ reinforcements * REINFORCE_PERCENT_CREATOR / 100
//less what has already been withdrawn;
- ownerWithdrawn;
require(toWithdraw > 0,"empty");
if(toWithdraw > address(this).balance){
//Catch rounding errors
toWithdraw = address(this).balance;
}
ownerWithdrawn += toWithdraw;
payable(msg.sender).send(toWithdraw);
}
function currentImpact() public view returns (int64[2] memory _coordinates, int64 _radius, bytes32 impactId){
uint eliminationBlock = block.number - (block.number % IMPACT_BLOCK_INTERVAL) - 5;
int hash = int(uint(blockhash(eliminationBlock))%uint(type(int).max) );
//Min radius is half map height divided by num
int o = MAP_HEIGHT/2/int(totalSupply()+1);
//Limited in smallness to about 8% of map height
if(o < BASE_BLAST_RADIUS){
o = BASE_BLAST_RADIUS;
}
//Max radius is twice this
_coordinates[0] = int64(hash%MAP_WIDTH - MAP_WIDTH/2);
_coordinates[1] = int64((hash/MAP_WIDTH)%MAP_HEIGHT - MAP_HEIGHT/2);
_radius = int64((hash/MAP_WIDTH/MAP_HEIGHT)%o + o);
return(_coordinates,_radius, keccak256(abi.encodePacked(_coordinates,_radius)));
}
function checkVulnerable(uint _tokenId, bytes32 _lastImpact) internal view returns(bool){
(int64[2] memory _coordinates, int64 _radius, bytes32 _impactId) = currentImpact();
if(_lastImpact == encodeImpact(_impactId)) return false;
uint16 _cityId = tokenToCity(_tokenId);
int64 dx = coordinates[_cityId][0] - _coordinates[0];
int64 dy = coordinates[_cityId][1] - _coordinates[1];
return (dx**2 + dy**2 < _radius**2) ||
((dx + MAP_WIDTH )**2 + dy**2 < _radius**2) ||
((dx - MAP_WIDTH )**2 + dy**2 < _radius**2);
}
function isVulnerable(uint _tokenId) public view returns(bool){
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
_reinforcement;_damage;
return checkVulnerable(_tokenId,_lastImpact);
}
function getFallen(uint _tokenId) public view returns(uint16 _cityId, address _owner){
_cityId = tokenToCity(_tokenId);
_owner = owners[_tokenId];
require(cityToToken[_cityId] == 0 && _owner != address(0),"survives");
return (_cityId,owners[_tokenId]);
}
function currentPrize() public view returns(uint){
uint cityCount = tokenIndexToCity.length;
// 50% of all mint fees collected
return MINT_COST * cityCount * MINT_PERCENT_WINNER / 100
//minus fees removed
- evacuatedFunds
//plus reinforcement * 90%
+ reinforcements * REINFORCE_PERCENT_WINNER / 100;
}
function winnerPrize(uint _tokenId) public view returns(uint){
return currentPrize() + getEvacuationRebate(_tokenId);
}
///ERC 721:
function isValidToken(uint256 _tokenId) internal view returns(bool){
if(_tokenId == 0) return false;
return cityToToken[tokenToCity(_tokenId)] != 0;
}
function balanceOf(address _owner) external override view returns (uint256){
return balances[_owner];
}
function ownerOf(uint256 _tokenId) public override view returns(address){
require(isValidToken(_tokenId),"invalid");
return owners[_tokenId];
}
function approve(address _approved, uint256 _tokenId) external override {
address _owner = ownerOf(_tokenId);
require( _owner == msg.sender //Require Sender Owns Token
|| authorised[_owner][msg.sender] // or is approved for all.
,"permission");
emit Approval(_owner, _approved, _tokenId);
allowance[_tokenId] = _approved;
}
function getApproved(uint256 _tokenId) external override view returns (address) {
require(isValidToken(_tokenId),"invalid");
return allowance[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) external override view returns (bool) {
return authorised[_owner][_operator];
}
function setApprovalForAll(address _operator, bool _approved) external override {
emit ApprovalForAll(msg.sender,_operator, _approved);
authorised[msg.sender][_operator] = _approved;
}
function transferFrom(address _from, address _to, uint256 _tokenId) public override {
//Check Transferable
//There is a token validity check in ownerOf
address _owner = ownerOf(_tokenId);
require ( _owner == msg.sender //Require sender owns token
//Doing the two below manually instead of referring to the external methods saves gas
|| allowance[_tokenId] == msg.sender //or is approved for this token
|| authorised[_owner][msg.sender] //or is approved for all
,"permission");
require(_owner == _from,"owner");
require(_to != address(0),"zero");
require(!isVulnerable(_tokenId),"vulnerable");
emit Transfer(_from, _to, _tokenId);
owners[_tokenId] =_to;
balances[_from]--;
balances[_to]++;
//Reset approved if there is one
if(allowance[_tokenId] != address(0)){
delete allowance[_tokenId];
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public override {
transferFrom(_from, _to, _tokenId);
//Get size of "_to" address, if 0 it's a wallet
uint32 size;
assembly {
size := extcodesize(_to)
}
if(size > 0){
IERC721Receiver receiver = IERC721Receiver(_to);
require(receiver.onERC721Received(msg.sender,_from,_tokenId,data) == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")),"receiver");
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override {
safeTransferFrom(_from,_to,_tokenId,"");
}
// METADATA FUNCTIONS
function tokenURI(uint256 _tokenId) public override view returns (string memory){
//Note: changed visibility to public
require(isValidToken(_tokenId),'tokenId');
uint _cityId = tokenToCity(_tokenId);
uint _i = _cityId;
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(abi.encodePacked(__uriBase,bstr,__uriSuffix));
}
function name() external override view returns (string memory _name){
return __name;
}
function symbol() external override view returns (string memory _symbol){
return __symbol;
}
// ENUMERABLE FUNCTIONS
function totalSupply() public view returns (uint256){
return tokenIndexToCity.length - destroyed;
}
// End 721 Implementation
///////===165 Implementation
mapping (bytes4 => bool) internal supportedInterfaces;
function supportsInterface(bytes4 interfaceID) external override view returns (bool){
return supportedInterfaces[interfaceID];
}
///==End 165
//Admin
function setOwner(address newOwner) public{
require(msg.sender == owner,"owner");
owner = newOwner;
}
function setUriComponents(string calldata _newBase, string calldata _newSuffix) public{
require(msg.sender == owner,"owner");
__uriBase = bytes(_newBase);
__uriSuffix = bytes(_newSuffix);
}
}
| mint the NFTFirst day is insiders list require(IERC721(earlyAccessHolders).balanceOf(msg.sender) > 0,"early"); | function inhabit(uint16 _cityId, int16[2] calldata _coordinates, bytes32[] memory proof) public payable{
require(stage() == Stage.PreSiege,"stage");
if(block.timestamp < startTime + EARLY_ACCESS_TIME){
}
bytes32 leaf = keccak256(abi.encodePacked(_cityId,_coordinates[0],_coordinates[1]));
require(MerkleProof.verify(proof, cityRoot, leaf),"proof");
require(cityToToken[_cityId] == 0 && coordinates[_cityId][0] == 0 && coordinates[_cityId][1] == 0,"inhabited");
require(
_coordinates[0] >= 0 &&
_coordinates[0] <= MAP_WIDTH &&
_coordinates[1] >= 0 &&
_coordinates[1] <= MAP_HEIGHT,
"off map"
console.log("msg.value", msg.value);
require(msg.value == MINT_COST,"cost");
coordinates[_cityId] = _coordinates;
tokenIndexToCity.push(_cityId);
uint _tokenId = tokenIndexToCity.length;
balances[msg.sender]++;
owners[_tokenId] = msg.sender;
cityToToken[_cityId] = _tokenId;
emit Inhabit(_cityId, _tokenId);
emit Transfer(address(0),msg.sender,_tokenId);
}
| 5,430,621 | [
1,
81,
474,
326,
423,
4464,
3759,
2548,
353,
2763,
24290,
666,
5411,
2583,
12,
45,
654,
39,
27,
5340,
12,
2091,
715,
1862,
27003,
2934,
12296,
951,
12,
3576,
18,
15330,
13,
405,
374,
10837,
2091,
715,
8863,
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,
316,
76,
30258,
12,
11890,
2313,
389,
14240,
548,
16,
509,
2313,
63,
22,
65,
745,
892,
389,
16941,
16,
1731,
1578,
8526,
3778,
14601,
13,
1071,
8843,
429,
95,
203,
3639,
2583,
12,
12869,
1435,
422,
16531,
18,
1386,
55,
1385,
908,
10837,
12869,
8863,
203,
3639,
309,
12,
2629,
18,
5508,
411,
8657,
397,
512,
985,
7076,
67,
13204,
67,
4684,
15329,
203,
3639,
289,
203,
203,
203,
3639,
1731,
1578,
7839,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
14240,
548,
16,
67,
16941,
63,
20,
6487,
67,
16941,
63,
21,
5717,
1769,
203,
203,
3639,
2583,
12,
8478,
15609,
20439,
18,
8705,
12,
24207,
16,
12797,
2375,
16,
7839,
3631,
6,
24207,
8863,
203,
203,
3639,
2583,
12,
14240,
774,
1345,
63,
67,
14240,
548,
65,
422,
374,
597,
5513,
63,
67,
14240,
548,
6362,
20,
65,
422,
374,
597,
5513,
63,
67,
14240,
548,
6362,
21,
65,
422,
374,
10837,
267,
76,
378,
16261,
8863,
203,
203,
3639,
2583,
12,
203,
5411,
389,
16941,
63,
20,
65,
1545,
374,
597,
203,
5411,
389,
16941,
63,
20,
65,
1648,
12815,
67,
10023,
597,
203,
203,
5411,
389,
16941,
63,
21,
65,
1545,
374,
597,
203,
5411,
389,
16941,
63,
21,
65,
1648,
12815,
67,
14595,
16,
203,
5411,
315,
3674,
852,
6,
203,
203,
3639,
2983,
18,
1330,
2932,
3576,
18,
1132,
3113,
1234,
18,
1132,
1769,
203,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
490,
3217,
67,
28343,
10837,
12398,
8863,
203,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-11
*/
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
interface ERC20 {
function totalSupply() external view returns (uint _totalSupply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function approve(address _spender, uint _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
interface IUniswapFactory {
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 IUniswapRouter01 {
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 factory() external pure returns (address);
function WETH() external pure returns (address);
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 IUniswapRouter02 is IUniswapRouter01 {
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 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;
}
contract smart {
address router_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapRouter02 router = IUniswapRouter02(router_address);
function create_weth_pair(address token) private returns (address, IUniswapV2Pair) {
address pair_address = IUniswapFactory(router.factory()).createPair(token, router.WETH());
return (pair_address, IUniswapV2Pair(pair_address));
}
function get_weth_reserve(address pair_address) private view returns(uint, uint) {
IUniswapV2Pair pair = IUniswapV2Pair(pair_address);
uint112 token_reserve;
uint112 native_reserve;
uint32 last_timestamp;
(token_reserve, native_reserve, last_timestamp) = pair.getReserves();
return (token_reserve, native_reserve);
}
function get_weth_price_impact(address token, uint amount, bool sell) private view returns(uint) {
address pair_address = IUniswapFactory(router.factory()).getPair(token, router.WETH());
(uint res_token, uint res_weth) = get_weth_reserve(pair_address);
uint impact;
if(sell) {
impact = (amount * 100) / res_token;
} else {
impact = (amount * 100) / res_weth;
}
return impact;
}
}
contract protected {
mapping (address => bool) is_auth;
function authorized(address addy) public view returns(bool) {
return is_auth[addy];
}
function set_authorized(address addy, bool booly) public onlyAuth {
is_auth[addy] = booly;
}
modifier onlyAuth() {
require( is_auth[msg.sender] || msg.sender==owner, "not owner");
_;
}
address owner;
modifier onlyOwner() {
require(msg.sender==owner, "not owner");
_;
}
bool locked;
modifier safe() {
require(!locked, "reentrant");
locked = true;
_;
locked = false;
}
receive() external payable {}
fallback() external payable {}
}
contract DLAND is protected, smart, ERC20 {
string public constant _name = 'DLAND';
string public constant _symbol = 'Democracy Land';
uint8 public constant _decimals = 18;
uint256 public constant InitialSupply= 7 * 10**9 * 10**_decimals;
uint256 public constant _circulatingSupply= InitialSupply;
address public constant UniswapRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant Dead = 0x000000000000000000000000000000000000dEaD;
event error_on_swap(bytes32 info);
bool trade_enabled;
mapping (address => uint256) public _balances;
mapping (address => mapping (address => uint256)) public _allowances;
address public pair;
IUniswapV2Pair public pair_contract;
IUniswapRouter02 public router_contract;
/// Balances
uint president_balance;
uint coder_balance;
uint liquidity_balance;
uint marketing_balance;
uint development_balance;
uint public president_eth_balance;
uint public coder_eth_balance;
uint public liquidity_eth_balance;
uint public marketing_eth_balance;
uint public development_eth_balance;
/// Fees and limits
bool public anti_bot = true;
bool public bot_crash = true;
uint public max_supply = (_circulatingSupply * 2)/100;
uint public initial_max_tx = (_circulatingSupply * 1) / 100;
uint public max_tx = (_circulatingSupply * 1) / 200;
uint public swap_treshold = (_circulatingSupply * 2) / 1000; /// @notice 0.2%
mapping(address => bool) public is_tax_free;
/// @dev To enable decimals, we use 10x values and then divide /1000
struct tax {
uint16 president;
uint16 coder;
uint16 liquidity;
uint16 marketing;
uint16 development;
}
mapping (bytes32 => tax) tax_on;
uint origin_time;
address president_wallet;
address marketing_wallet;
address coder_wallet;
address development_wallet;
constructor() {
owner = msg.sender;
is_auth[owner] = true;
origin_time = block.timestamp;
is_tax_free[owner] = true;
tax_on["buy"].president = 10;
tax_on["buy"].coder = 5;
tax_on["buy"].liquidity = 2;
tax_on["buy"].marketing = 3;
tax_on["buy"].development = 3;
tax_on["sell"].president = 10;
tax_on["sell"].coder = 5;
tax_on["sell"].liquidity = 3;
tax_on["sell"].marketing = 3;
tax_on["sell"].development = 4;
tax_on["sell_before_one_hour"].president = 30;
tax_on["sell_before_one_hour"].coder = 5;
tax_on["sell_before_one_hour"].liquidity = 40;
tax_on["sell_before_one_hour"].marketing = 80;
tax_on["sell_before_one_hour"].development = 90;
tax_on["sell_before_two_hours"].president = 20;
tax_on["sell_before_two_hours"].coder = 5;
tax_on["sell_before_two_hours"].liquidity = 30;
tax_on["sell_before_two_hours"].marketing = 50;
tax_on["sell_before_two_hours"].development = 50;
_balances[msg.sender] = InitialSupply;
emit Transfer(Dead, msg.sender, InitialSupply);
}
function _transfer(address sender, address recipient, uint amount) private {
bytes32 destination;
bool isBuy=sender== pair|| sender == router_address;
bool isSell=recipient== pair|| recipient == router_address;
uint current_time = block.timestamp;
uint time_diff = current_time - origin_time;
bool is_excluded = (is_tax_free[sender] || is_tax_free[recipient]) || is_auth[sender] || is_auth[recipient];
bool is_contract_transfer=(sender==address(this) || recipient==address(this));
bool is_liquidity_transfer = ((sender == pair && recipient == router_address)
|| (recipient == pair && sender == router_address));
if(is_excluded || is_liquidity_transfer || is_contract_transfer) {
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
return;
}
/// @dev IMPORTANT: this function allows to block snipers without them noticing
/// basically seizing the money they are using to cheat.
/// Is fundamental to educate users and mods to avoid unexpected losses.
if(!bot_crash) {
require(trade_enabled, "Trade disabled");
} else {
emit Transfer(sender, recipient, 0);
return;
}
if(isBuy) {
destination = "buy";
} else if (isSell) {
if (time_diff < 2 hours) {
if(time_diff < 1 hours) {
destination = "sell_before_one_hour";
} else {
destination = "sell_before_two_hours";
}
} else {
destination = "sell";
}
}
uint taxed_amount = apply_taxes(amount, destination);
uint tax_taken = amount - taxed_amount;
_balances[sender] -= amount;
_balances[recipient] += taxed_amount;
_balances[address(this)] += tax_taken;
emit Transfer(sender, recipient, taxed_amount);
emit Transfer(sender, address(this), tax_taken);
if((_balances[address(this)] >= swap_treshold) && isSell) {
swap_tokens(amount);
}
}
function apply_taxes(uint amount, bytes32 destination) private returns(uint) {
uint _taxed_;
(uint _president,
uint _coder,
uint _liquidity,
uint _marketing,
uint _development) = get_tax_on(destination);
/// @dev The /1000 calculation is done to counter the absence of floating numbers
uint president_tokens = (amount * _president) / 1000;
uint coder_tokens = (amount * _coder) / 1000;
uint liquidity_tokens = (amount * _liquidity) / 1000;
uint marketing_tokens = (amount * _marketing) / 1000;
uint development_tokens = (amount * _development) / 1000;
president_balance += president_tokens;
coder_balance += coder_tokens;
liquidity_balance += liquidity_tokens;
marketing_balance += marketing_tokens;
development_balance += development_tokens;
return _taxed_;
}
function swap_tokens(uint sell_size) private {
/// @dev avoid honeypotting if contract has no tokens
if(!(address(this).balance > 0)) {
emit error_on_swap("insufficient funds");
return;
}
uint token_to_sell = _balances[address(this)];
if(token_to_sell > sell_size) {
token_to_sell = sell_size;
}
address[] memory path;
path[0] = (address(this));
path[1] = (router.WETH());
uint liquidity_to_sell = (liquidity_balance/2);
uint liquidity_to_add = (liquidity_balance - liquidity_to_sell);
uint president_share = (president_balance * 100) / token_to_sell;
uint coder_share = (coder_balance * 100) / token_to_sell;
uint liquidity_share = (liquidity_to_sell * 100) / token_to_sell;
uint marketing_share = (marketing_balance * 100) / token_to_sell;
uint development_share = (development_balance * 100) / token_to_sell;
uint total_shares = president_share + coder_share + liquidity_share +
marketing_share + development_share;
/// @dev solves the imprecision of rounded numbers in solidity
if(total_shares > 100) {
marketing_share -= (total_shares - 100);
} else if (total_shares < 100) {
marketing_share += (100 - total_shares);
}
uint previous_balance = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
token_to_sell,
0,
path,
address(this),
block.timestamp
);
uint new_balance = address(this).balance;
uint earned = new_balance - previous_balance;
uint liquidity_earnings = (earned * liquidity_share) / 100;
uint marketing_earnings = (earned * marketing_share) / 100;
uint president_earnings = (earned * liquidity_share) / 100;
uint coder_earnings = (earned * liquidity_share) / 100;
uint development_earnings = (earned * liquidity_share) / 100;
add_liquidity(liquidity_to_add, liquidity_earnings);
marketing_eth_balance += marketing_earnings;
president_eth_balance += president_earnings;
coder_eth_balance += coder_earnings;
development_eth_balance += development_earnings;
}
function add_liquidity(uint liquidity_to_add, uint liquidity_earnings) private {
/// @dev adding liquidity
_approve(address(this), router_address, liquidity_to_add);
router.addLiquidityETH {value:liquidity_earnings} (
address(this),
liquidity_to_add,
0,
0,
address(this),
block.timestamp);
}
function set_president_wallet(address wallet) public onlyAuth {
president_wallet = wallet;
}
function set_coder_wallet(address wallet) public onlyAuth {
coder_wallet = wallet;
}
function set_marketing_wallet(address wallet) public onlyAuth {
marketing_wallet = wallet;
}
function set_development_wallet(address wallet) public onlyAuth {
development_wallet = wallet;
}
function retrieve_president() public onlyAuth {
require(address(this).balance >= president_balance, "Insufficient amount");
(bool sent,) = president_wallet.call{value: president_balance}("");
require(sent, "Failed to transfer");
president_balance = 0;
}
function retrieve_marketing() public onlyAuth {
require(address(this).balance >= marketing_balance, "Insufficient amount");
(bool sent,) = marketing_wallet.call{value: marketing_balance}("");
require(sent, "Failed to transfer");
marketing_balance = 0;
}
function retrieve_development() public onlyAuth {
require(address(this).balance >= development_balance, "Insufficient amount");
(bool sent,) = development_wallet.call{value: development_balance}("");
require(sent, "Failed to transfer");
development_balance = 0;
}
function retrieve_coder() public onlyAuth {
require(address(this).balance >= coder_balance, "Insufficient amount");
(bool sent,) = coder_wallet.call{value: coder_balance}("");
require(sent, "Failed to transfer");
coder_balance = 0;
}
function avoid_locks() public onlyAuth {
(bool sent,) = msg.sender.call{value: address(this).balance}("");
require(sent, "Failed to transfer");
}
function rescue(address tknAddress) public onlyAuth {
ERC20 token = ERC20(tknAddress);
uint256 ourBalance = token.balanceOf(address(this));
require(ourBalance>0, "No tokens in our balance");
token.transfer(msg.sender, ourBalance);
}
function set_tax_on(bytes32 destination, uint16 _president, uint16 _coder, uint16 _liquidity,
uint16 _marketing, uint16 _development) public onlyAuth {
tax_on[destination].president = _president;
tax_on[destination].coder = _coder;
tax_on[destination].liquidity = _liquidity;
tax_on[destination].marketing = _marketing;
tax_on[destination].development = _development;
}
function get_tax_on(bytes32 destination) public view returns(uint16, uint16, uint16,
uint16 ,uint16) {
return(
tax_on[destination].president,
tax_on[destination].coder,
tax_on[destination].liquidity,
tax_on[destination].marketing,
tax_on[destination].development
);
}
function set_tax_free(address actor, bool state) public onlyAuth {
is_tax_free[actor] = state;
}
function sell_tokens() public onlyAuth {
swap_tokens(_balances[address(this)]);
}
function enable_trading() public onlyAuth {
trade_enabled = true;
}
function getOwner() external view returns (address) {
return owner;
}
function name() external pure returns (string memory) {
return _name;
}
function symbol() external pure returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return _decimals;
}
function totalSupply() pure public override returns (uint256) {
return _circulatingSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address _owner, address spender) external view override returns (uint256) {
return _allowances[_owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function _approve(address _owner, address spender, uint256 amount) private {
require(_owner != address(0), "Approve from zero");
require(spender != address(0), "Approve to zero");
_allowances[_owner][spender] = amount;
emit Approval(_owner, spender, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "Transfer > allowance");
_approve(sender, msg.sender, currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "<0 allowance");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
} | Balances Fees and limits @dev To enable decimals, we use 10x values and then divide /1000 | struct tax {
uint16 president;
uint16 coder;
uint16 liquidity;
uint16 marketing;
uint16 development;
}
mapping (bytes32 => tax) tax_on;
uint origin_time;
address president_wallet;
address marketing_wallet;
address coder_wallet;
address development_wallet;
| 15,104,982 | [
1,
38,
26488,
5782,
281,
471,
8181,
225,
2974,
4237,
15105,
16,
732,
999,
1728,
92,
924,
471,
1508,
12326,
342,
18088,
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
] | [
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,
0
] | [
1,
565,
1958,
5320,
288,
203,
3639,
2254,
2313,
4075,
6392,
31,
203,
3639,
2254,
2313,
276,
5350,
31,
203,
3639,
2254,
2313,
4501,
372,
24237,
31,
203,
3639,
2254,
2313,
13667,
310,
31,
203,
3639,
2254,
2313,
17772,
31,
203,
565,
289,
203,
203,
565,
2874,
261,
3890,
1578,
516,
5320,
13,
5320,
67,
265,
31,
203,
203,
565,
2254,
4026,
67,
957,
31,
203,
203,
565,
1758,
4075,
6392,
67,
19177,
31,
203,
565,
1758,
13667,
310,
67,
19177,
31,
203,
565,
1758,
276,
5350,
67,
19177,
31,
203,
565,
1758,
17772,
67,
19177,
31,
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
] |
./full_match/4/0x0A7a3f0696c36E5c3452915dbB1b3115c3A37680/sources/browser/3_Ballot.sol | putting safeguard on will halt all non-owner functions
| bool public safeguard; | 671,033 | [
1,
458,
1787,
11029,
1332,
89,
1060,
603,
903,
18389,
777,
1661,
17,
8443,
4186,
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,
1426,
1071,
11029,
1332,
89,
1060,
31,
282,
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
] |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.13;
/**
.o. . .o8
.888. .o8 "888
.8"888. .oooo.o .o888oo oooo d8b .ooooo. .oooo888 oooo d8b .ooooo. oo.ooooo.
.8' `888. d88( "8 888 `888""8P d88' `88b d88' `888 `888""8P d88' `88b 888' `88b
.88ooo8888. `"Y88b. 888 888 888 888 888 888 888 888 888 888 888
.8' `888. o. )88b 888 . 888 888 888 888 888 888 888 888 888 888
o88o o8888o 8""888P' "888" d888b `Y8bod8P' `Y8bod88P" d888b `Y8bod8P' 888bod8P'
888
o888o
*/
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { ERC20 } from "@rari-capital/solmate/src/tokens/ERC20.sol";
import { SafeTransferLib } from "@rari-capital/solmate/src/utils/SafeTransferLib.sol";
import { Ownable } from "./lib/Ownable.sol";
import { ReentrancyGuard } from "./lib/ReentrancyGuard.sol";
/// @title Shrine
/// @author zefram.eth
/// @notice A Shrine maintains a list of Champions with individual weights (shares), and anyone could
/// offer any ERC-20 tokens to the Shrine in order to distribute them to the Champions proportional to their
/// shares. A Champion transfer their right to claim all future tokens offered to
/// the Champion to another address.
contract Shrine is Ownable, ReentrancyGuard {
/// -----------------------------------------------------------------------
/// Errors
/// -----------------------------------------------------------------------
error Shrine_AlreadyInitialized();
error Shrine_InputArraysLengthMismatch();
error Shrine_NotAuthorized();
error Shrine_InvalidMerkleProof();
error Shrine_LedgerZeroTotalShares();
/// -----------------------------------------------------------------------
/// Custom types
/// -----------------------------------------------------------------------
type Champion is address;
type Version is uint256;
/// -----------------------------------------------------------------------
/// Library usage
/// -----------------------------------------------------------------------
using SafeTransferLib for ERC20;
/// -----------------------------------------------------------------------
/// Events
/// -----------------------------------------------------------------------
event Offer(address indexed sender, ERC20 indexed token, uint256 amount);
event Claim(
address recipient,
Version indexed version,
ERC20 indexed token,
Champion indexed champion,
uint256 claimedTokenAmount
);
event ClaimFromMetaShrine(Shrine indexed metaShrine);
event TransferChampionStatus(Champion indexed champion, address recipient);
event UpdateLedger(Version indexed newVersion, Ledger newLedger);
event UpdateLedgerMetadata(
Version indexed version,
string newLedgerMetadataIPFSHash
);
/// -----------------------------------------------------------------------
/// Structs
/// -----------------------------------------------------------------------
/// @param version The Merkle tree version
/// @param token The ERC-20 token to be claimed
/// @param champion The Champion address. If the Champion rights have been transferred, the tokens will be sent to its owner.
/// @param shares The share amount of the Champion
/// @param merkleProof The Merkle proof showing the Champion is part of this Shrine's Merkle tree
struct ClaimInfo {
Version version;
ERC20 token;
Champion champion;
uint256 shares;
bytes32[] merkleProof;
}
/// @param metaShrine The shrine to claim from
/// @param version The Merkle tree version
/// @param token The ERC-20 token to be claimed
/// @param shares The share amount of the Champion
/// @param merkleProof The Merkle proof showing the Champion is part of this Shrine's Merkle tree
struct MetaShrineClaimInfo {
Shrine metaShrine;
Version version;
ERC20 token;
uint256 shares;
bytes32[] merkleProof;
}
struct Ledger {
bytes32 merkleRoot;
uint256 totalShares;
}
/// -----------------------------------------------------------------------
/// Storage variables
/// -----------------------------------------------------------------------
/// @notice The current version of the ledger, starting from 1
Version public currentLedgerVersion;
/// @notice version => ledger
mapping(Version => Ledger) public ledgerOfVersion;
/// @notice version => (token => (champion => claimedTokens))
mapping(Version => mapping(ERC20 => mapping(Champion => uint256)))
public claimedTokens;
/// @notice version => (token => offeredTokens)
mapping(Version => mapping(ERC20 => uint256)) public offeredTokens;
/// @notice champion => address
mapping(Champion => address) public championClaimRightOwner;
/// -----------------------------------------------------------------------
/// Initialization
/// -----------------------------------------------------------------------
/// @notice Initialize the Shrine contract.
/// @param initialGuardian The Shrine's initial guardian, who controls the ledger
/// @param initialLedger The Shrine's initial ledger with the distribution shares
/// @param initialLedgerMetadataIPFSHash The IPFS hash of the initial metadata
function initialize(
address initialGuardian,
Ledger calldata initialLedger,
string calldata initialLedgerMetadataIPFSHash
) external {
// we use currentLedgerVersion as a flag for whether the Shrine
// has already been initialized
if (Version.unwrap(currentLedgerVersion) != 0) {
revert Shrine_AlreadyInitialized();
}
// 0 total shares makes no sense
if (initialLedger.totalShares == 0)
revert Shrine_LedgerZeroTotalShares();
__ReentrancyGuard_init();
__Ownable_init(initialGuardian);
// the version number start at 1
currentLedgerVersion = Version.wrap(1);
ledgerOfVersion[Version.wrap(1)] = initialLedger;
// emit event to let indexers pick up ledger & metadata IPFS hash
emit UpdateLedger(Version.wrap(1), initialLedger);
emit UpdateLedgerMetadata(
Version.wrap(1),
initialLedgerMetadataIPFSHash
);
}
/// -----------------------------------------------------------------------
/// User actions
/// -----------------------------------------------------------------------
/// @notice Offer ERC-20 tokens to the Shrine and distribute them to Champions proportional
/// to their shares in the Shrine. Callable by anyone.
/// @param token The ERC-20 token being offered to the Shrine
/// @param amount The amount of tokens to offer
function offer(ERC20 token, uint256 amount) external {
// -------------------------------------------------------------------
// State updates
// -------------------------------------------------------------------
// distribute tokens to Champions
offeredTokens[currentLedgerVersion][token] += amount;
// -------------------------------------------------------------------
// Effects
// -------------------------------------------------------------------
// transfer tokens from sender
token.safeTransferFrom(msg.sender, address(this), amount);
emit Offer(msg.sender, token, amount);
}
/// @notice Offer multiple ERC-20 tokens to the Shrine and distribute them to Champions proportional
/// to their shares in the Shrine. The input arrays must be of the same length. Callable by anyone.
/// @param versionList The list of ledger versions to distribute to
/// @param tokenList The list of ERC-20 tokens being offered to the Shrine
/// @param amountList The list of amounts of tokens to offer
function offerMultiple(
Version[] calldata versionList,
ERC20[] calldata tokenList,
uint256[] calldata amountList
) external {
// -------------------------------------------------------------------
// Validation
// -------------------------------------------------------------------
if (
versionList.length != tokenList.length ||
versionList.length != amountList.length
) {
revert Shrine_InputArraysLengthMismatch();
}
// -------------------------------------------------------------------
// State updates
// -------------------------------------------------------------------
for (uint256 i = 0; i < versionList.length; i++) {
// distribute tokens to Champions
offeredTokens[versionList[i]][tokenList[i]] += amountList[i];
}
// -------------------------------------------------------------------
// Effects
// -------------------------------------------------------------------
for (uint256 i = 0; i < versionList.length; i++) {
// transfer tokens from sender
tokenList[i].safeTransferFrom(
msg.sender,
address(this),
amountList[i]
);
emit Offer(msg.sender, tokenList[i], amountList[i]);
}
}
/// @notice A Champion or the owner of a Champion may call this to claim their share of the tokens offered to this Shrine.
/// Requires a Merkle proof to prove that the Champion is part of this Shrine's Merkle tree.
/// Only callable by the champion (if the right was never transferred) or the owner
/// (that the original champion transferred their rights to)
/// @param claimInfo The info of the claim
/// @return claimedTokenAmount The amount of tokens claimed
function claim(address recipient, ClaimInfo calldata claimInfo)
external
returns (uint256 claimedTokenAmount)
{
// -------------------------------------------------------------------
// Validation
// -------------------------------------------------------------------
// verify sender auth
_verifyChampionOwnership(claimInfo.champion);
// verify Merkle proof that the champion is part of the Merkle tree
_verifyMerkleProof(
claimInfo.version,
claimInfo.champion,
claimInfo.shares,
claimInfo.merkleProof
);
// compute claimable amount
uint256 championClaimedTokens = claimedTokens[claimInfo.version][
claimInfo.token
][claimInfo.champion];
claimedTokenAmount = _computeClaimableTokenAmount(
claimInfo.version,
claimInfo.token,
claimInfo.shares,
championClaimedTokens
);
// -------------------------------------------------------------------
// State updates
// -------------------------------------------------------------------
// record total tokens claimed by the champion
claimedTokens[claimInfo.version][claimInfo.token][claimInfo.champion] =
championClaimedTokens +
claimedTokenAmount;
// -------------------------------------------------------------------
// Effects
// -------------------------------------------------------------------
// transfer tokens to the recipient
claimInfo.token.safeTransfer(recipient, claimedTokenAmount);
emit Claim(
recipient,
claimInfo.version,
claimInfo.token,
claimInfo.champion,
claimedTokenAmount
);
}
/// @notice A variant of {claim} that combines multiple claims into a single call.
function claimMultiple(
address recipient,
ClaimInfo[] calldata claimInfoList
) external returns (uint256[] memory claimedTokenAmountList) {
claimedTokenAmountList = new uint256[](claimInfoList.length);
for (uint256 i = 0; i < claimInfoList.length; i++) {
// -------------------------------------------------------------------
// Validation
// -------------------------------------------------------------------
// verify sender auth
_verifyChampionOwnership(claimInfoList[i].champion);
// verify Merkle proof that the champion is part of the Merkle tree
_verifyMerkleProof(
claimInfoList[i].version,
claimInfoList[i].champion,
claimInfoList[i].shares,
claimInfoList[i].merkleProof
);
// compute claimable amount
uint256 championClaimedTokens = claimedTokens[
claimInfoList[i].version
][claimInfoList[i].token][claimInfoList[i].champion];
claimedTokenAmountList[i] = _computeClaimableTokenAmount(
claimInfoList[i].version,
claimInfoList[i].token,
claimInfoList[i].shares,
championClaimedTokens
);
// -------------------------------------------------------------------
// State updates
// -------------------------------------------------------------------
// record total tokens claimed by the champion
claimedTokens[claimInfoList[i].version][claimInfoList[i].token][
claimInfoList[i].champion
] = championClaimedTokens + claimedTokenAmountList[i];
}
for (uint256 i = 0; i < claimInfoList.length; i++) {
// -------------------------------------------------------------------
// Effects
// -------------------------------------------------------------------
// transfer tokens to the recipient
claimInfoList[i].token.safeTransfer(
recipient,
claimedTokenAmountList[i]
);
emit Claim(
recipient,
claimInfoList[i].version,
claimInfoList[i].token,
claimInfoList[i].champion,
claimedTokenAmountList[i]
);
}
}
/// @notice A variant of {claim} that combines multiple claims for the same Champion & version into a single call.
/// @dev This is more efficient than {claimMultiple} since it only checks Champion ownership & verifies Merkle proof once.
function claimMultipleTokensForChampion(
address recipient,
Version version,
ERC20[] calldata tokenList,
Champion champion,
uint256 shares,
bytes32[] calldata merkleProof
) external returns (uint256[] memory claimedTokenAmountList) {
// -------------------------------------------------------------------
// Validation
// -------------------------------------------------------------------
// verify sender auth
_verifyChampionOwnership(champion);
// verify Merkle proof that the champion is part of the Merkle tree
_verifyMerkleProof(version, champion, shares, merkleProof);
claimedTokenAmountList = new uint256[](tokenList.length);
for (uint256 i = 0; i < tokenList.length; i++) {
// compute claimable amount
uint256 championClaimedTokens = claimedTokens[version][
tokenList[i]
][champion];
claimedTokenAmountList[i] = _computeClaimableTokenAmount(
version,
tokenList[i],
shares,
championClaimedTokens
);
// -------------------------------------------------------------------
// State updates
// -------------------------------------------------------------------
// record total tokens claimed by the champion
claimedTokens[version][tokenList[i]][champion] =
championClaimedTokens +
claimedTokenAmountList[i];
}
for (uint256 i = 0; i < tokenList.length; i++) {
// -------------------------------------------------------------------
// Effects
// -------------------------------------------------------------------
// transfer tokens to the recipient
tokenList[i].safeTransfer(recipient, claimedTokenAmountList[i]);
emit Claim(
recipient,
version,
tokenList[i],
champion,
claimedTokenAmountList[i]
);
}
}
/// @notice If this Shrine is a Champion of another Shrine (MetaShrine), calling this can claim the tokens
/// from the MetaShrine and distribute them to this Shrine's Champions. Callable by anyone.
/// @param claimInfo The info of the claim
/// @return claimedTokenAmount The amount of tokens claimed
function claimFromMetaShrine(MetaShrineClaimInfo calldata claimInfo)
external
nonReentrant
returns (uint256 claimedTokenAmount)
{
return _claimFromMetaShrine(claimInfo);
}
/// @notice A variant of {claimFromMetaShrine} that combines multiple claims into a single call.
function claimMultipleFromMetaShrine(
MetaShrineClaimInfo[] calldata claimInfoList
) external nonReentrant returns (uint256[] memory claimedTokenAmountList) {
// claim and distribute tokens
claimedTokenAmountList = new uint256[](claimInfoList.length);
for (uint256 i = 0; i < claimInfoList.length; i++) {
claimedTokenAmountList[i] = _claimFromMetaShrine(claimInfoList[i]);
}
}
/// @notice Allows a champion to transfer their right to claim from this shrine to
/// another address. The champion will effectively lose their shrine membership, so
/// make sure the new owner is a trusted party.
/// Only callable by the champion (if the right was never transferred) or the owner
/// (that the original champion transferred their rights to)
/// @param champion The champion whose claim rights will be transferred away
/// @param newOwner The address that will receive all rights of the champion
function transferChampionClaimRight(Champion champion, address newOwner)
external
{
// -------------------------------------------------------------------
// Validation
// -------------------------------------------------------------------
// verify sender auth
_verifyChampionOwnership(champion);
// -------------------------------------------------------------------
// State updates
// -------------------------------------------------------------------
championClaimRightOwner[champion] = newOwner;
emit TransferChampionStatus(champion, newOwner);
}
/// -----------------------------------------------------------------------
/// Getters
/// -----------------------------------------------------------------------
/// @notice Computes the amount of a particular ERC-20 token claimable by a Champion from
/// a particular version of the Merkle tree.
/// @param version The Merkle tree version
/// @param token The ERC-20 token to be claimed
/// @param champion The Champion address
/// @param shares The share amount of the Champion
/// @return claimableTokenAmount The amount of tokens claimable
function computeClaimableTokenAmount(
Version version,
ERC20 token,
Champion champion,
uint256 shares
) public view returns (uint256 claimableTokenAmount) {
return
_computeClaimableTokenAmount(
version,
token,
shares,
claimedTokens[version][token][champion]
);
}
/// @notice The Shrine Guardian's address (same as the contract owner)
/// @return The Guardian's address
function guardian() external view returns (address) {
return owner();
}
/// @notice The ledger at a particular version
/// @param version The version of the ledger to query
/// @return The ledger at the specified version
function getLedgerOfVersion(Version version)
external
view
returns (Ledger memory)
{
return ledgerOfVersion[version];
}
/// -----------------------------------------------------------------------
/// Guardian actions
/// -----------------------------------------------------------------------
/// @notice The Guardian may call this function to update the ledger, so that the list of
/// champions and the associated weights are updated.
/// @param newLedger The new Merkle tree to use for the list of champions and their shares
function updateLedger(Ledger calldata newLedger) external onlyOwner {
// 0 total shares makes no sense
if (newLedger.totalShares == 0) revert Shrine_LedgerZeroTotalShares();
Version newVersion = Version.wrap(
Version.unwrap(currentLedgerVersion) + 1
);
currentLedgerVersion = newVersion;
ledgerOfVersion[newVersion] = newLedger;
emit UpdateLedger(newVersion, newLedger);
}
/// @notice The Guardian may call this function to update the ledger metadata IPFS hash.
/// @dev This function simply emits the IPFS hash in an event, so that an off-chain indexer
/// can pick it up.
/// @param newLedgerMetadataIPFSHash The IPFS hash of the updated metadata
function updateLedgerMetadata(
Version version,
string calldata newLedgerMetadataIPFSHash
) external onlyOwner {
emit UpdateLedgerMetadata(version, newLedgerMetadataIPFSHash);
}
/// -----------------------------------------------------------------------
/// Internal utilities
/// -----------------------------------------------------------------------
/// @dev Reverts if the sender isn't the champion or does not own the champion claim right
/// @param champion The champion whose ownership will be verified
function _verifyChampionOwnership(Champion champion) internal view {
{
address _championClaimRightOwner = championClaimRightOwner[
champion
];
if (_championClaimRightOwner == address(0)) {
// claim right not transferred, sender should be the champion
if (msg.sender != Champion.unwrap(champion))
revert Shrine_NotAuthorized();
} else {
// claim right transferred, sender should be the owner
if (msg.sender != _championClaimRightOwner)
revert Shrine_NotAuthorized();
}
}
}
/// @dev Reverts if the champion is not part of the Merkle tree
/// @param version The Merkle tree version
/// @param champion The Champion address. If the Champion rights have been transferred, the tokens will be sent to its owner.
/// @param shares The share amount of the Champion
/// @param merkleProof The Merkle proof showing the Champion is part of this Shrine's Merkle tree
function _verifyMerkleProof(
Version version,
Champion champion,
uint256 shares,
bytes32[] calldata merkleProof
) internal view {
if (
!MerkleProof.verify(
merkleProof,
ledgerOfVersion[version].merkleRoot,
keccak256(abi.encodePacked(champion, shares))
)
) {
revert Shrine_InvalidMerkleProof();
}
}
/// @dev See {computeClaimableTokenAmount}
function _computeClaimableTokenAmount(
Version version,
ERC20 token,
uint256 shares,
uint256 claimedTokenAmount
) internal view returns (uint256 claimableTokenAmount) {
uint256 totalShares = ledgerOfVersion[version].totalShares;
uint256 offeredTokenAmount = (offeredTokens[version][token] * shares) /
totalShares;
// rounding may cause (offeredTokenAmount < claimedTokenAmount)
// don't want to revert because of it
claimableTokenAmount = offeredTokenAmount >= claimedTokenAmount
? offeredTokenAmount - claimedTokenAmount
: 0;
}
/// @dev See {claimFromMetaShrine}
function _claimFromMetaShrine(MetaShrineClaimInfo calldata claimInfo)
internal
returns (uint256 claimedTokenAmount)
{
// -------------------------------------------------------------------
// Effects
// -------------------------------------------------------------------
// claim tokens from the meta shrine
uint256 beforeBalance = claimInfo.token.balanceOf(address(this));
claimInfo.metaShrine.claim(
address(this),
ClaimInfo({
version: claimInfo.version,
token: claimInfo.token,
champion: Champion.wrap(address(this)),
shares: claimInfo.shares,
merkleProof: claimInfo.merkleProof
})
);
claimedTokenAmount =
claimInfo.token.balanceOf(address(this)) -
beforeBalance;
// -------------------------------------------------------------------
// State updates
// -------------------------------------------------------------------
// distribute tokens to Champions
offeredTokens[currentLedgerVersion][
claimInfo.token
] += claimedTokenAmount;
emit Offer(
address(claimInfo.metaShrine),
claimInfo.token,
claimedTokenAmount
);
emit ClaimFromMetaShrine(claimInfo.metaShrine);
}
}
| @notice Offer ERC-20 tokens to the Shrine and distribute them to Champions proportional to their shares in the Shrine. Callable by anyone. @param token The ERC-20 token being offered to the Shrine @param amount The amount of tokens to offer ------------------------------------------------------------------- State updates ------------------------------------------------------------------- distribute tokens to Champions ------------------------------------------------------------------- Effects ------------------------------------------------------------------- transfer tokens from sender | function offer(ERC20 token, uint256 amount) external {
offeredTokens[currentLedgerVersion][token] += amount;
token.safeTransferFrom(msg.sender, address(this), amount);
emit Offer(msg.sender, token, amount);
}
| 15,818,196 | [
1,
10513,
4232,
39,
17,
3462,
2430,
358,
326,
2638,
86,
558,
471,
25722,
2182,
358,
1680,
931,
1115,
23279,
287,
358,
3675,
24123,
316,
326,
2638,
86,
558,
18,
10464,
635,
1281,
476,
18,
225,
1147,
1021,
4232,
39,
17,
3462,
1147,
3832,
10067,
329,
358,
326,
2638,
86,
558,
225,
3844,
1021,
3844,
434,
2430,
358,
10067,
8879,
413,
3287,
4533,
8879,
413,
25722,
2430,
358,
1680,
931,
1115,
8879,
413,
30755,
87,
8879,
413,
7412,
2430,
628,
5793,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
10067,
12,
654,
39,
3462,
1147,
16,
2254,
5034,
3844,
13,
3903,
288,
203,
203,
3639,
10067,
329,
5157,
63,
2972,
28731,
1444,
6362,
2316,
65,
1011,
3844,
31,
203,
203,
203,
3639,
1147,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
203,
3639,
3626,
25753,
12,
3576,
18,
15330,
16,
1147,
16,
3844,
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
] |
pragma solidity ^0.5.4;
import "./AuctionityLibrary_V1.sol";
/// @title AuctionityOracable_V1
contract AuctionityOracable_V1 is AuctionityLibrary_V1 {
/// @notice event LogOracleTransfered_V1
event LogOracleTransfered_V1(
address indexed previousOracle,
address indexed newOracle
);
/// @notice delegate receive of getOracle
/// @return _oracle address
function delegatedReceiveGetOracle_V1()
public
payable
returns (address _oracle)
{
return getOracle_V1();
}
/// @notice getter oracle address
/// @return _oracle address
function getOracle_V1() public view returns (address _oracle) {
return oracle;
}
/// @notice verify if msg.sender is oracle
/// @return _isOracle bool
function isOracle_V1() public view returns (bool _isOracle) {
return msg.sender == oracle;
}
/**
* @return true if `_oracle` is the oracle of the contract.
*/
/// @notice verify oracle address
/// @param _oracle address : address to compare
/// @return _isOracle bool
function verifyOracle_V1(address _oracle)
public
view
returns (bool _isOracle)
{
return _oracle == oracle;
}
/// @notice Allows the current oracle or owner to set a new oracle.
/// @param _newOracle The address to transfer oracleship to.
function transferOracle_V1(address _newOracle) public {
require(
isOracle_V1() || delegatedSendIsContractOwner_V1(),
"Is not Oracle or Owner"
);
_transferOracle_V1(_newOracle);
}
/// @notice Transfers control of the contract to a newOracle.
/// @param _newOracle The address to transfer oracleship to.
function _transferOracle_V1(address _newOracle) internal {
require(_newOracle != address(0), "Oracle can't be 0x0");
emit LogOracleTransfered_V1(oracle, _newOracle);
oracle = _newOracle;
}
}
| @notice verify oracle address @param _oracle address : address to compare @return _isOracle bool | function verifyOracle_V1(address _oracle)
public
view
returns (bool _isOracle)
{
return _oracle == oracle;
}
| 919,274 | [
1,
8705,
20865,
1758,
225,
389,
280,
16066,
1758,
294,
1758,
358,
3400,
327,
389,
291,
23601,
1426,
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,
3929,
23601,
67,
58,
21,
12,
2867,
389,
280,
16066,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
389,
291,
23601,
13,
203,
565,
288,
203,
3639,
327,
389,
280,
16066,
422,
20865,
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
] |
//Address: 0x65d08c27d696eb55170cb3346b423ad85e58de68
//Contract name: CSCRarePreSaleManager
//Balance: 145.914409625771604941 Ether
//Verification Date: 4/5/2018
//Transacion Count: 29
// CODE STARTS HERE
pragma solidity ^0.4.19;
/* Adapted from strings.sol created by Nick Johnson <[email protected]>
* Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*/
library strings {
struct slice {
uint _len;
uint _ptr;
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string self) internal pure returns (slice) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
function concat(slice self, slice other) internal returns (string) {
var ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice self, slice needle) internal returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) {
uint ptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 68 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
let end := add(selfptr, sub(selflen, needlelen))
ptr := selfptr
loop:
jumpi(exit, eq(and(mload(ptr), mask), needledata))
ptr := add(ptr, 1)
jumpi(loop, lt(sub(ptr, 1), end))
ptr := add(selfptr, selflen)
exit:
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := sha3(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice self, slice needle, slice token) internal returns (slice) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice self, slice needle) internal returns (slice token) {
split(self, needle, token);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice self) internal pure returns (string) {
var ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
}
/* Helper String Functions for Game Manager Contract
* @title String Healpers
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
*/
contract StringHelpers {
using strings for *;
function stringToBytes32(string memory source) internal returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function bytes32ToString(bytes32 x) constant internal returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _assetId) public view returns (address owner);
function approve(address _to, uint256 _assetId) public;
function transfer(address _to, uint256 _assetId) public;
function transferFrom(address _from, address _to, uint256 _assetId) public;
function implementsERC721() public pure returns (bool);
function takeOwnership(uint256 _assetId) public;
function totalSupply() public view returns (uint256 total);
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _assetId) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/* Controls game play state and access rights for game functions
* @title Operational Control
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
* Inspired and adapted from contract created by OpenZeppelin
* Ref: https://github.com/OpenZeppelin/zeppelin-solidity/
*/
contract OperationalControl {
// Facilitates access & control for the game.
// Roles:
// -The Game Managers (Primary/Secondary): Has universal control of all game elements (No ability to withdraw)
// -The Banker: The Bank can withdraw funds and adjust fees / prices.
/// @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public gameManagerPrimary;
address public gameManagerSecondary;
address public bankManager;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
// @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed
bool public error = false;
/// @dev Operation modifiers for limiting access
modifier onlyGameManager() {
require(msg.sender == gameManagerPrimary || msg.sender == gameManagerSecondary);
_;
}
modifier onlyBanker() {
require(msg.sender == bankManager);
_;
}
modifier anyOperator() {
require(
msg.sender == gameManagerPrimary ||
msg.sender == gameManagerSecondary ||
msg.sender == bankManager
);
_;
}
/// @dev Assigns a new address to act as the GM.
function setPrimaryGameManager(address _newGM) external onlyGameManager {
require(_newGM != address(0));
gameManagerPrimary = _newGM;
}
/// @dev Assigns a new address to act as the GM.
function setSecondaryGameManager(address _newGM) external onlyGameManager {
require(_newGM != address(0));
gameManagerSecondary = _newGM;
}
/// @dev Assigns a new address to act as the Banker.
function setBanker(address _newBK) external onlyGameManager {
require(_newBK != address(0));
bankManager = _newBK;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Modifier to allow actions only when the contract has Error
modifier whenError {
require(error);
_;
}
/// @dev Called by any Operator role to pause the contract.
/// Used only if a bug or exploit is discovered (Here to limit losses / damage)
function pause() external onlyGameManager whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the Game Master
/// @notice This is public rather than external so it can be called by derived contracts.
function unpause() public onlyGameManager whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
/// @dev Unpauses the smart contract. Can only be called by the Game Master
/// @notice This is public rather than external so it can be called by derived contracts.
function hasError() public onlyGameManager whenPaused {
error = true;
}
/// @dev Unpauses the smart contract. Can only be called by the Game Master
/// @notice This is public rather than external so it can be called by derived contracts.
function noError() public onlyGameManager whenPaused {
error = false;
}
}
contract CSCCollectibleBase is ERC721, OperationalControl, StringHelpers {
/*** EVENTS ***/
/// @dev The Created event is fired whenever a new collectible comes into existence.
event CollectibleCreated(address owner, uint256 collectibleId, bytes32 collectibleName, bool isRedeemed);
event Transfer(address from, address to, uint256 shipId);
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CSCRareCollectiblePreSale";
string public constant SYMBOL = "CSCR";
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @dev CSC Pre Sale Struct, having details of the ship
struct RarePreSaleItem {
/// @dev name of the collectible stored in bytes
bytes32 collectibleName;
/// @dev Timestamp when bought
uint256 boughtTimestamp;
// @dev owner address
address owner;
// @dev redeeme flag (to help whether it got redeemed or not)
bool isRedeemed;
}
// @dev array of RarePreSaleItem type holding information on the Ships
RarePreSaleItem[] allPreSaleItems;
// @dev mapping which holds all the possible addresses which are allowed to interact with the contract
mapping (address => bool) approvedAddressList;
// @dev mapping holds the preSaleItem -> owner details
mapping (uint256 => address) public preSaleItemIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) private ownershipTokenCount;
/// @dev A mapping from preSaleItem to an address that has been approved to call
/// transferFrom(). Each Ship can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public preSaleItemIndexToApproved;
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _assetId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _assetId) public {
// Caller must own token.
require(_owns(address(this), _assetId));
preSaleItemIndexToApproved[_assetId] = _to;
Approval(msg.sender, _to, _assetId);
}
/// For querying balance of a particular account
/// @param _owner The address for balance query
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
function implementsERC721() public pure returns (bool) {
return true;
}
/// For querying owner of token
/// @param _assetId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _assetId) public view returns (address owner) {
owner = preSaleItemIndexToOwner[_assetId];
require(owner != address(0));
}
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns (string) {
return SYMBOL;
}
/// @notice Allow pre-approved user to take ownership of a token
/// @param _assetId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _assetId) public {
address newOwner = msg.sender;
address oldOwner = preSaleItemIndexToOwner[_assetId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _assetId));
_transfer(oldOwner, newOwner, _assetId);
}
/// @param _owner The owner whose ships tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire CSCShips array looking for emojis belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalShips = totalSupply() + 1;
uint256 resultIndex = 0;
// We count on the fact that all CSC Ship Collectible have IDs starting at 0 and increasing
// sequentially up to the total count.
uint256 _assetId;
for (_assetId = 0; _assetId < totalShips; _assetId++) {
if (preSaleItemIndexToOwner[_assetId] == _owner) {
result[resultIndex] = _assetId;
resultIndex++;
}
}
return result;
}
}
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) {
return allPreSaleItems.length - 1; //Removed 0 index
}
/// Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _assetId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _assetId) public {
require(_addressNotNull(_to));
require(_owns(msg.sender, _assetId));
_transfer(msg.sender, _to, _assetId);
}
/// Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _assetId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint256 _assetId) public {
require(_owns(_from, _assetId));
require(_approved(_to, _assetId));
require(_addressNotNull(_to));
_transfer(_from, _to, _assetId);
}
/*** PRIVATE FUNCTIONS ***/
/// @dev Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) internal pure returns (bool) {
return _to != address(0);
}
/// @dev For checking approval of transfer for address _to
function _approved(address _to, uint256 _assetId) internal view returns (bool) {
return preSaleItemIndexToApproved[_assetId] == _to;
}
/// @dev For creating CSC Collectible
function _createCollectible(bytes32 _collectibleName, address _owner) internal returns(uint256) {
RarePreSaleItem memory _collectibleObj = RarePreSaleItem(
_collectibleName,
0,
address(0),
false
);
uint256 newCollectibleId = allPreSaleItems.push(_collectibleObj) - 1;
// emit Created event
CollectibleCreated(_owner, newCollectibleId, _collectibleName, false);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newCollectibleId);
return newCollectibleId;
}
/// Check for token ownership
function _owns(address claimant, uint256 _assetId) internal view returns (bool) {
return claimant == preSaleItemIndexToOwner[_assetId];
}
/// @dev Assigns ownership of a specific Emoji to an address.
function _transfer(address _from, address _to, uint256 _assetId) internal {
// Updating the owner details of the ship
RarePreSaleItem memory _shipObj = allPreSaleItems[_assetId];
_shipObj.owner = _to;
allPreSaleItems[_assetId] = _shipObj;
// Since the number of emojis is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
preSaleItemIndexToOwner[_assetId] = _to;
// When creating new emojis _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete preSaleItemIndexToApproved[_assetId];
}
// Emit the transfer event.
Transfer(_from, _to, _assetId);
}
/// @dev Checks if a given address currently has transferApproval for a particular RarePreSaleItem.
/// 0 is a valid value as it will be the starter
function _approvedFor(address _claimant, uint256 _assetId) internal view returns (bool) {
return preSaleItemIndexToApproved[_assetId] == _claimant;
}
function _getCollectibleDetails (uint256 _assetId) internal view returns(RarePreSaleItem) {
RarePreSaleItem storage _Obj = allPreSaleItems[_assetId];
return _Obj;
}
/// @dev Helps in fetching the attributes of the ship depending on the ship
/// assetId : The actual ERC721 Asset ID
/// sequenceId : Index w.r.t Ship type
function getShipDetails(uint256 _assetId) external view returns (
uint256 collectibleId,
string shipName,
uint256 boughtTimestamp,
address owner,
bool isRedeemed
) {
RarePreSaleItem storage _collectibleObj = allPreSaleItems[_assetId];
collectibleId = _assetId;
shipName = bytes32ToString(_collectibleObj.collectibleName);
boughtTimestamp = _collectibleObj.boughtTimestamp;
owner = _collectibleObj.owner;
isRedeemed = _collectibleObj.isRedeemed;
}
}
/* Lucid Sight, Inc. ERC-721 CSC Collectilbe Sale Contract.
* @title CSCCollectibleSale
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
*/
contract CSCCollectibleSale is CSCCollectibleBase {
event SaleWinner(address owner, uint256 collectibleId, uint256 buyingPrice);
event CollectibleBidSuccess(address owner, uint256 collectibleId, uint256 newBidPrice, bool isActive);
event SaleCreated(uint256 tokenID, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint64 startedAt, bool isActive, uint256 bidPrice);
// SHIP DATATYPES & CONSTANTS
struct CollectibleSale {
// Current owner of NFT (ERC721)
address seller;
// Price (in wei) at beginning of sale (For Buying)
uint256 startingPrice;
// Price (in wei) at end of sale (For Buying)
uint256 endingPrice;
// Duration (in seconds) of sale
uint256 duration;
// Time when sale started
// NOTE: 0 if this sale has been concluded
uint64 startedAt;
// Flag denoting is the Sale stilla ctive
bool isActive;
// address of the wallet who had the maxBid
address highestBidder;
// address of the wallet who bought the asset
address buyer;
// ERC721 AssetID
uint256 tokenId;
}
// @dev ship Prices & price cap
uint256 public constant SALE_DURATION = 2592000;
/// mapping holding details of the last person who had a successfull bid. used for giving back the last bid price until the asset is bought
mapping(uint256 => address) indexToBidderAddress;
mapping(address => mapping(uint256 => uint256)) addressToBidValue;
// A map from assetId to the bid increment
mapping ( uint256 => uint256 ) indexToPriceIncrement;
/// Map from assetId to bid price
mapping ( uint256 => uint256 ) indexToBidPrice;
// Map from token to their corresponding sale.
mapping (uint256 => CollectibleSale) tokenIdToSale;
/// @dev Adds an sale to the list of open sales. Also fires the
/// SaleCreated event.
function _addSale(uint256 _assetId, CollectibleSale _sale) internal {
// Require that all sales have a duration of
// at least one minute.
require(_sale.duration >= 1 minutes);
tokenIdToSale[_assetId] = _sale;
indexToBidPrice[_assetId] = _sale.endingPrice;
SaleCreated(
uint256(_assetId),
uint256(_sale.startingPrice),
uint256(_sale.endingPrice),
uint256(_sale.duration),
uint64(_sale.startedAt),
_sale.isActive,
indexToBidPrice[_assetId]
);
}
/// @dev Removes an sale from the list of open sales.
/// @param _assetId - ID of the token on sale
function _removeSale(uint256 _assetId) internal {
delete tokenIdToSale[_assetId];
}
function _bid(uint256 _assetId, address _buyer, uint256 _bidAmount) internal {
CollectibleSale storage _sale = tokenIdToSale[_assetId];
require(_bidAmount >= indexToBidPrice[_assetId]);
uint256 _newBidPrice = _bidAmount + indexToPriceIncrement[_assetId];
indexToBidPrice[_assetId] = _newBidPrice;
_sale.highestBidder = _buyer;
_sale.endingPrice = _newBidPrice;
address lastBidder = indexToBidderAddress[_assetId];
if(lastBidder != address(0)){
uint256 _value = addressToBidValue[lastBidder][_assetId];
indexToBidderAddress[_assetId] = _buyer;
addressToBidValue[lastBidder][_assetId] = 0;
addressToBidValue[_buyer][_assetId] = _bidAmount;
lastBidder.transfer(_value);
} else {
indexToBidderAddress[_assetId] = _buyer;
addressToBidValue[_buyer][_assetId] = _bidAmount;
}
// Check that the bid is greater than or equal to the current buyOut price
uint256 price = _currentPrice(_sale);
if(_bidAmount >= price) {
_sale.buyer = _buyer;
_sale.isActive = false;
_removeSale(_assetId);
uint256 bidExcess = _bidAmount - price;
_buyer.transfer(bidExcess);
SaleWinner(_buyer, _assetId, _bidAmount);
_transfer(address(this), _buyer, _assetId);
} else {
tokenIdToSale[_assetId] = _sale;
CollectibleBidSuccess(_buyer, _assetId, _sale.endingPrice, _sale.isActive);
}
}
/// @dev Returns true if the FT (ERC721) is on sale.
function _isOnSale(CollectibleSale memory _sale) internal view returns (bool) {
return (_sale.startedAt > 0 && _sale.isActive);
}
/// @dev Returns current price of a Collectible (ERC721) on sale. Broken into two
/// functions (this one, that computes the duration from the sale
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(CollectibleSale memory _sale) internal view returns (uint256) {
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _sale.startedAt) {
secondsPassed = now - _sale.startedAt;
}
return _computeCurrentPrice(
_sale.startingPrice,
_sale.endingPrice,
_sale.duration,
secondsPassed
);
}
/// @dev Computes the current price of an sale. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addSale())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the sale, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Escrows the ERC721 Token, assigning ownership to this contract.
/// Throws if the escrow fails.
function _escrow(address _owner, uint256 _tokenId) internal {
transferFrom(_owner, this, _tokenId);
}
function getBuyPrice(uint256 _assetId) external view returns(uint256 _price){
CollectibleSale memory _sale = tokenIdToSale[_assetId];
return _currentPrice(_sale);
}
function getBidPrice(uint256 _assetId) external view returns(uint256 _price){
return indexToBidPrice[_assetId];
}
/// @dev Creates and begins a new sale.
function _createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) internal {
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the sale struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
CollectibleSale memory sale = CollectibleSale(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now),
true,
address(this),
address(this),
uint256(_tokenId)
);
_addSale(_tokenId, sale);
}
function _buy(uint256 _assetId, address _buyer, uint256 _price) internal {
CollectibleSale storage _sale = tokenIdToSale[_assetId];
address lastBidder = indexToBidderAddress[_assetId];
if(lastBidder != address(0)){
uint256 _value = addressToBidValue[lastBidder][_assetId];
indexToBidderAddress[_assetId] = _buyer;
addressToBidValue[lastBidder][_assetId] = 0;
addressToBidValue[_buyer][_assetId] = _price;
lastBidder.transfer(_value);
}
// Check that the bid is greater than or equal to the current buyOut price
uint256 currentPrice = _currentPrice(_sale);
require(_price >= currentPrice);
_sale.buyer = _buyer;
_sale.isActive = false;
_removeSale(_assetId);
uint256 bidExcess = _price - currentPrice;
_buyer.transfer(bidExcess);
SaleWinner(_buyer, _assetId, _price);
_transfer(address(this), _buyer, _assetId);
}
/// @dev Returns sales info for an CSLCollectibles (ERC721) on sale.
/// @param _assetId - ID of the token on sale
function getSale(uint256 _assetId) external view returns (address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, bool isActive, address owner, address highestBidder) {
CollectibleSale memory sale = tokenIdToSale[_assetId];
require(_isOnSale(sale));
return (
sale.seller,
sale.startingPrice,
sale.endingPrice,
sale.duration,
sale.startedAt,
sale.isActive,
sale.buyer,
sale.highestBidder
);
}
}
/* Lucid Sight, Inc. ERC-721 Collectibles.
* @title LSNFT - Lucid Sight, Inc. Non-Fungible Token
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
*/
contract CSCRarePreSaleManager is CSCCollectibleSale {
event RefundClaimed(address owner);
bool CSCPreSaleInit = false;
/// @dev Constructor creates a reference to the NFT (ERC721) ownership contract
function CSCRarePreSaleManager() public {
require(msg.sender != address(0));
paused = true;
error = false;
gameManagerPrimary = msg.sender;
}
function addToApprovedAddress (address _newAddr) onlyGameManager {
require(_newAddr != address(0));
require(!approvedAddressList[_newAddr]);
approvedAddressList[_newAddr] = true;
}
function removeFromApprovedAddress (address _newAddr) onlyGameManager {
require(_newAddr != address(0));
require(approvedAddressList[_newAddr]);
approvedAddressList[_newAddr] = false;
}
function createPreSaleShip(string collectibleName, uint256 startingPrice, uint256 bidPrice) whenNotPaused returns (uint256){
require(approvedAddressList[msg.sender] || msg.sender == gameManagerPrimary || msg.sender == gameManagerSecondary);
uint256 assetId = _createCollectible(stringToBytes32(collectibleName), address(this));
indexToPriceIncrement[assetId] = bidPrice;
_createSale(assetId, startingPrice, bidPrice, uint64(SALE_DURATION), address(this));
}
function() external payable {
}
/// @dev Bid Function which call the interncal bid function
/// after doing all the pre-checks required to initiate a bid
function bid(uint256 _assetId) external whenNotPaused payable {
require(msg.sender != address(0));
require(msg.sender != address(this));
CollectibleSale memory _sale = tokenIdToSale[_assetId];
require(_isOnSale(_sale));
address seller = _sale.seller;
_bid(_assetId, msg.sender, msg.value);
}
/// @dev BuyNow Function which call the interncal buy function
/// after doing all the pre-checks required to initiate a buy
function buyNow(uint256 _assetId) external whenNotPaused payable {
require(msg.sender != address(0));
require(msg.sender != address(this));
CollectibleSale memory _sale = tokenIdToSale[_assetId];
require(_isOnSale(_sale));
address seller = _sale.seller;
_buy(_assetId, msg.sender, msg.value);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyGameManager whenPaused {
// Actually unpause the contract.
super.unpause();
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT (ERC721) contract, but can be called either by
/// the owner or the NFT (ERC721) contract.
function withdrawBalance() onlyBanker {
// We are using this boolean method to make sure that even if one fails it will still work
bankManager.transfer(this.balance);
}
function preSaleInit() onlyGameManager {
require(!CSCPreSaleInit);
require(allPreSaleItems.length == 0);
CSCPreSaleInit = true;
bytes32[6] memory attributes = [bytes32(999), bytes32(999), bytes32(999), bytes32(999), bytes32(999), bytes32(999)];
//Fill in index 0 to null requests
RarePreSaleItem memory _Obj = RarePreSaleItem(stringToBytes32("Dummy"), 0, address(this), true);
allPreSaleItems.push(_Obj);
}
}
| @dev Creates and begins a new sale. Sanity check that no inputs overflow how many bits we've allocated to store them in the sale struct. | function _createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) internal {
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
CollectibleSale memory sale = CollectibleSale(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now),
true,
address(this),
address(this),
uint256(_tokenId)
);
_addSale(_tokenId, sale);
}
| 6,344,697 | [
1,
2729,
471,
17874,
279,
394,
272,
5349,
18,
23123,
866,
716,
1158,
4540,
9391,
3661,
4906,
4125,
732,
8081,
11977,
358,
1707,
2182,
316,
326,
272,
5349,
1958,
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,
445,
389,
2640,
30746,
12,
11890,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
18526,
5147,
16,
2254,
5034,
389,
2846,
5147,
16,
2254,
1105,
389,
8760,
16,
1758,
389,
1786,
749,
13,
2713,
288,
203,
1377,
2583,
24899,
18526,
5147,
422,
2254,
5034,
12,
11890,
10392,
24899,
18526,
5147,
3719,
1769,
203,
1377,
2583,
24899,
2846,
5147,
422,
2254,
5034,
12,
11890,
10392,
24899,
2846,
5147,
3719,
1769,
203,
1377,
2583,
24899,
8760,
422,
2254,
5034,
12,
11890,
1105,
24899,
8760,
3719,
1769,
203,
203,
1377,
9302,
1523,
30746,
3778,
272,
5349,
273,
9302,
1523,
30746,
12,
203,
1850,
389,
1786,
749,
16,
203,
1850,
2254,
10392,
24899,
18526,
5147,
3631,
203,
1850,
2254,
10392,
24899,
2846,
5147,
3631,
203,
1850,
2254,
1105,
24899,
8760,
3631,
203,
1850,
2254,
1105,
12,
3338,
3631,
203,
1850,
638,
16,
203,
1850,
1758,
12,
2211,
3631,
203,
1850,
1758,
12,
2211,
3631,
203,
1850,
2254,
5034,
24899,
2316,
548,
13,
203,
1377,
11272,
203,
1377,
389,
1289,
30746,
24899,
2316,
548,
16,
272,
5349,
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
] |
./full_match/1/0x18faf3cdF637D6054C64fE76cEA218C6e009c261/sources/contracts/interfaces/IDogMoneyAuctionHouse.sol | The id of this auction. The package containing which tokens are to be auctioned. The current highest bid amount. The time that the auction started. The time that the auction is scheduled to end. The address of the current highest bid. Whether or not the auction has been settled. If there isn't balance for an auction, or it was made erroneously, then the auction operator can cancel it. Used to recycle through old auctions. | struct Auction {
uint256 id;
AuctionPack auctionPack;
uint256 amount;
uint256 startTime;
uint256 endTime;
address payable bidder;
bool settled;
bool cancelled;
uint256 lastAttempt;
}
| 8,448,319 | [
1,
1986,
612,
434,
333,
279,
4062,
18,
1021,
2181,
4191,
1492,
2430,
854,
358,
506,
279,
4062,
329,
18,
1021,
783,
9742,
9949,
3844,
18,
1021,
813,
716,
326,
279,
4062,
5746,
18,
1021,
813,
716,
326,
279,
4062,
353,
9755,
358,
679,
18,
1021,
1758,
434,
326,
783,
9742,
9949,
18,
17403,
578,
486,
326,
279,
4062,
711,
2118,
26319,
1259,
18,
971,
1915,
5177,
1404,
11013,
364,
392,
279,
4062,
16,
578,
518,
1703,
7165,
393,
476,
1481,
715,
16,
1508,
326,
279,
4062,
3726,
848,
3755,
518,
18,
10286,
358,
23493,
3059,
1592,
279,
4062,
87,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
1958,
432,
4062,
288,
203,
3639,
2254,
5034,
612,
31,
203,
3639,
432,
4062,
4420,
279,
4062,
4420,
31,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
2254,
5034,
8657,
31,
203,
3639,
2254,
5034,
13859,
31,
203,
3639,
1758,
8843,
429,
9949,
765,
31,
203,
3639,
1426,
26319,
1259,
31,
203,
3639,
1426,
13927,
31,
203,
3639,
2254,
5034,
1142,
7744,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-24
*/
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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/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/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(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 {}
/**
* @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.
* - `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 tokenId
) 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: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
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;
}
}
// File: hardhat/console.sol
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File: v1phunks.sol
/**
does NOT admit json extension in ipfs
*/
pragma solidity ^0.8.0;
contract V1Phunks is ERC721, Ownable {
using Counters for Counters.Counter;
using SafeMath for uint256;
Counters.Counter private _tokenIds;
uint256 public constant MAX_SUPPLY = 10000; //10.000 V1 Phunks
uint256 public constant MAX_PER_MINT = 10;
uint256 private constant MAX_RESERVED_MINTS = 500;
uint256 public FREE_STAGE_MINTING= 250;
uint256 private FREE_STAGE_PRICE= 0 ether;
uint256 public PUBLIC_PRICE= 0.015 ether;
uint256 private RESERVED_MINTS = 0;
bool public paused = false;
string public baseTokenURI = "ipfs://QmYxKmX5SXfGxwgrrfNvxxEXdbxaTQn9yy3JQx15p5cwgo/";
constructor() ERC721("V1 Phunks", "V1PHNK") {
setBaseURI(baseTokenURI);
_mintSingleNFT();
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function setBaseURI(string memory _baseTokenURI) public onlyOwner {
baseTokenURI = _baseTokenURI;
}
function mintNFTs(uint _number) public payable {
uint256 totalMinted = _tokenIds.current();
require(!paused, "Sale Paused") ;
require(totalMinted.add(_number) <= MAX_SUPPLY - MAX_RESERVED_MINTS, "Not enough V1 Phunks remaining!");
require(_number > 0 && _number <= MAX_PER_MINT, "Cannot mint specified number of V1 Phunks.");
require(msg.value >= Price() * _number, "Not enough ether to purchase V1 Phunks.");
for (uint i = 0; i < _number; i++) {
_mintSingleNFT();
}
}
function _mintSingleNFT() private {
uint newTokenID = _tokenIds.current();
_safeMint(msg.sender, newTokenID);
_tokenIds.increment();
}
//in case ETH price gets too high; expressed in ETH x 10^18
function setPrice(uint256 _price) external onlyOwner {
PUBLIC_PRICE = _price;
}
function Price() private view returns(uint256) {
uint256 totalMinted = _tokenIds.current();
if ( totalMinted < FREE_STAGE_MINTING) {
return FREE_STAGE_PRICE;
} else {
return PUBLIC_PRICE;
}
}
function setFreeMints(uint256 freeStageNum) external onlyOwner {
FREE_STAGE_MINTING = freeStageNum;
}
function reserveNFTs(uint256 _number) public onlyOwner {
uint256 totalMinted = _tokenIds.current();
require((totalMinted.add(_number)) <= MAX_SUPPLY, "Exceeds V1 Phunks supply");
require(RESERVED_MINTS + _number <= MAX_RESERVED_MINTS, "Exceeds reserved V1 Phunks supply");
for (uint256 i = 0; i < _number; i++) {
_mintSingleNFT();
}
RESERVED_MINTS = RESERVED_MINTS + _number;
}
//Withdraw money in contract to Owner
function withdraw() public payable onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "No ether left to withdraw");
(bool success, ) = (msg.sender).call{value: balance}("");
require(success, "Transfer failed.");
}
function giveAway(address _to, uint256 _amount) external onlyOwner() {
require( _amount + RESERVED_MINTS <= MAX_RESERVED_MINTS, "Exceeds reserved V1 Phunk supply" );
uint newTokenID = _tokenIds.current();
for(uint256 i; i < _amount; i++){
_safeMint(_to, newTokenID);
_tokenIds.increment();
}
RESERVED_MINTS += _amount;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function totalSupply() external view returns(uint256) {
return _tokenIds.current() ;
}
} | in case ETH price gets too high; expressed in ETH x 10^18 | function setPrice(uint256 _price) external onlyOwner {
PUBLIC_PRICE = _price;
}
| 10,611,167 | [
1,
267,
648,
512,
2455,
6205,
5571,
4885,
3551,
31,
26863,
316,
512,
2455,
619,
1728,
66,
2643,
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,
444,
5147,
12,
11890,
5034,
389,
8694,
13,
3903,
1338,
5541,
288,
203,
3639,
17187,
67,
7698,
1441,
273,
389,
8694,
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
] |
./full_match/1/0xCF810239F6266316D4Cfe2E478cD8d6be03ae1A6/sources/contracts/Comptroller.sol | * @notice Set the COMP token address @param _comp The COMP address/ | function _setCompAddress(address _comp) public {
require(msg.sender == admin, "only admin can set comp");
comp = _comp;
}
| 4,943,420 | [
1,
694,
326,
13846,
1147,
1758,
225,
389,
2919,
1021,
13846,
1758,
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,
565,
445,
389,
542,
2945,
1887,
12,
2867,
389,
2919,
13,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3981,
16,
315,
3700,
3981,
848,
444,
1161,
8863,
203,
3639,
1161,
273,
389,
2919,
31,
203,
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
] |
./partial_match/97/0x6315329068FC855F224D09924A11EA266EfF4486/sources/CLIQ.sol | function to performs staking for user tokens for a specific period of time | function stakeToken2(uint256 tokens, uint256 time) public returns(bool){
require( time > now && tokens > 0, "Invalid time and Amount");
_stakingCount = _stakingCount +1 ;
_time = now + (time * 1 days);
_totalDays[_stakingCount] = time;
_stakingAddress[_stakingCount] = msg.sender;
_stakingEndTime[_stakingCount] = time;
_stakingStartTime[_stakingCount] = now;
_usersTokens[_stakingCount] = tokens;
_stakingStatus[_stakingCount] = true;
_transfer(msg.sender, _tokenStakePoolAddress, tokens);
return true;
}
| 11,461,417 | [
1,
915,
358,
11199,
384,
6159,
364,
729,
2430,
364,
279,
2923,
3879,
434,
813,
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,
225,
445,
384,
911,
1345,
22,
12,
11890,
5034,
2430,
16,
2254,
5034,
813,
13,
1071,
1135,
12,
6430,
15329,
203,
565,
2583,
12,
813,
405,
2037,
597,
2430,
405,
374,
16,
315,
1941,
813,
471,
16811,
8863,
203,
565,
389,
334,
6159,
1380,
273,
389,
334,
6159,
1380,
397,
21,
274,
203,
565,
389,
957,
273,
2037,
397,
261,
957,
380,
404,
4681,
1769,
203,
565,
389,
4963,
9384,
63,
67,
334,
6159,
1380,
65,
273,
813,
31,
203,
565,
389,
334,
6159,
1887,
63,
67,
334,
6159,
1380,
65,
273,
1234,
18,
15330,
31,
203,
565,
389,
334,
6159,
25255,
63,
67,
334,
6159,
1380,
65,
273,
813,
31,
203,
565,
389,
334,
6159,
13649,
63,
67,
334,
6159,
1380,
65,
273,
2037,
31,
203,
565,
389,
5577,
5157,
63,
67,
334,
6159,
1380,
65,
273,
2430,
31,
203,
565,
389,
334,
6159,
1482,
63,
67,
334,
6159,
1380,
65,
273,
638,
31,
203,
565,
389,
13866,
12,
3576,
18,
15330,
16,
389,
2316,
510,
911,
2864,
1887,
16,
2430,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
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
] |
pragma solidity ^0.4.18;
// CONTRACT USED TO TEST THE ICO CONTRACT
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
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);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
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;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
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];
}
}
/**
* @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];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
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 IprontoToken is StandardToken {
// Setting Token Name to Mango
string public constant name = "iPRONTO";
// Setting Token Symbol to MGO
string public constant symbol = "IPR";
// Setting Token Decimals to 18
uint8 public constant decimals = 18;
// Setting Token Decimals to 45 Million
uint256 public constant INITIAL_SUPPLY = 45000000 * (1 ether / 1 wei);
address public owner;
// Flags address for KYC verrified.
mapping (address => bool) public validKyc;
function IprontoToken() public{
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Approving an address to tranfer tokens
function approveKyc(address[] _addrs)
public
onlyOwner
returns (bool)
{
uint len = _addrs.length;
while (len-- > 0) {
validKyc[_addrs[len]] = true;
}
return true;
}
function isValidKyc(address _addr) public constant returns (bool){
return validKyc[_addr];
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(isValidKyc(msg.sender));
return super.approve(_spender, _value);
}
function() public{
throw;
}
} | Setting Token Name to Mango Setting Token Symbol to MGO Setting Token Decimals to 18 Setting Token Decimals to 45 Million Flags address for KYC verrified. | contract IprontoToken is StandardToken {
string public constant name = "iPRONTO";
string public constant symbol = "IPR";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 45000000 * (1 ether / 1 wei);
address public owner;
mapping (address => bool) public validKyc;
function IprontoToken() public{
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function approveKyc(address[] _addrs)
public
onlyOwner
returns (bool)
{
uint len = _addrs.length;
while (len-- > 0) {
validKyc[_addrs[len]] = true;
}
return true;
}
function approveKyc(address[] _addrs)
public
onlyOwner
returns (bool)
{
uint len = _addrs.length;
while (len-- > 0) {
validKyc[_addrs[len]] = true;
}
return true;
}
function isValidKyc(address _addr) public constant returns (bool){
return validKyc[_addr];
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(isValidKyc(msg.sender));
return super.approve(_spender, _value);
}
function() public{
throw;
}
} | 2,362,134 | [
1,
5568,
3155,
1770,
358,
490,
6399,
13274,
3155,
8565,
358,
490,
16387,
13274,
3155,
3416,
11366,
358,
6549,
13274,
3155,
3416,
11366,
358,
12292,
490,
737,
285,
10104,
1758,
364,
1475,
61,
39,
331,
370,
939,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
467,
683,
265,
869,
1345,
353,
8263,
1345,
288,
203,
203,
225,
533,
1071,
5381,
508,
273,
315,
77,
8025,
673,
4296,
14432,
203,
203,
225,
533,
1071,
5381,
3273,
273,
315,
2579,
54,
14432,
203,
203,
225,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
203,
225,
2254,
5034,
1071,
5381,
28226,
67,
13272,
23893,
273,
12292,
9449,
380,
261,
21,
225,
2437,
342,
404,
732,
77,
1769,
203,
203,
225,
1758,
1071,
3410,
31,
203,
203,
225,
2874,
261,
2867,
516,
1426,
13,
1071,
923,
47,
93,
71,
31,
203,
203,
225,
445,
467,
683,
265,
869,
1345,
1435,
1071,
95,
203,
565,
2078,
3088,
1283,
273,
28226,
67,
13272,
23893,
31,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
273,
28226,
67,
13272,
23893,
31,
203,
565,
3410,
273,
1234,
18,
15330,
31,
203,
225,
289,
203,
203,
225,
9606,
1338,
5541,
1435,
288,
203,
565,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
445,
6617,
537,
47,
93,
71,
12,
2867,
8526,
389,
23305,
13,
203,
3639,
1071,
203,
3639,
1338,
5541,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2254,
562,
273,
389,
23305,
18,
2469,
31,
203,
3639,
1323,
261,
1897,
413,
405,
374,
13,
288,
203,
5411,
923,
47,
93,
71,
63,
67,
23305,
63,
1897,
13563,
273,
638,
31,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
225,
445,
6617,
537,
47,
93,
71,
12,
2
] |
// SPDX-License-Identifier: MIT
// CBOX Agent for getting items from given vault
//
// .. . . ..
// @@@@& &@@@@@@@@@@@@@@@( @@@@@.
// @@@@& [email protected]@@@@@@@@@@@@@@@@@@@@@@@@. @@@@@.
// @@@@& @@@@@@@@ @@@@@@@@ @@@@@.
// @@@@@@@@@@.. ,@@@@@@@@@@.
// @@@@@@@@ [email protected]@@@@@@@.
// @@@@@@. %@@@@@@.
// @@@@@. %@@@@@.
// @@@@@ @@@@@.
// [email protected]@@@& C-BOX @@@@@
// @@@@@ A G E N T @@@@@.
// /@@@@, .&@@@@..
// @@@@@/ @@@@@(
// %@@@@@.. [email protected]@@@@.
// [email protected]@@@@@,. #@@@@@@
// [email protected]@@@@@@@... . ,@@@@@@@@
// . @@@@@@@@@@@@@@@@@@@@@@@@&
// [email protected]@@@@@@@@@@@@@@..
//
//
// @creator: ConiunIO
// @security: [email protected]
// @author: Batuhan KATIRCI (@batuhan_katirci)
// @website: https://coniun.io/
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
error InvalidSignature(string message);
error ExpiredSignature(string message);
error ReceiverMismatch(string message);
error TransferError(string message);
error PermissionError(string message);
error DuplicateEntryError(string message);
contract CBOXAgent is Ownable, Pausable {
event CBOXClaimed(
uint256 indexed cboxWeek,
address indexed owner,
uint256 indexed passId,
address contractAddress,
uint256 tokenId
);
using ECDSA for bytes32;
address private _signerAddress;
address private _coniunContractAddress;
// weekIndex -> (passId -> claimed)
mapping(uint256 => mapping(uint256 => bool)) private _cboxClaims;
constructor(address signerAddress, address coniunContractAddress) {
_signerAddress = signerAddress;
_coniunContractAddress = coniunContractAddress;
}
function setSignerAddress(address signerAddress) public onlyOwner {
_signerAddress = signerAddress;
}
function claimToken(
address vaultAddress,
address contractAddress,
uint256 tokenId,
uint256 passId,
uint256 cboxWeek,
bytes memory signature
) public whenNotPaused {
// Disallow contract calls
if (msg.sender != tx.origin) {
revert PermissionError("Contract calls is not allowed");
}
// Check if cbox already claimed in given week index
if (_cboxClaims[cboxWeek][passId] == true) {
revert DuplicateEntryError("This C-BOX is already claimed");
}
// Verify signature agaisnt backend signer address
if (
verifySignature(
vaultAddress,
msg.sender,
contractAddress,
tokenId,
passId,
cboxWeek,
signature
) != true
) {
revert InvalidSignature("Signature verification failed");
}
_cboxClaims[cboxWeek][passId] = true;
// initiate proxies
ERC721Proxy proxy = ERC721Proxy(contractAddress);
ERC721Proxy coniunProxy = ERC721Proxy(_coniunContractAddress);
// check if msg.sender still owns that eligible cbox
if (coniunProxy.ownerOf(passId) != msg.sender) {
revert ReceiverMismatch("C-BOX owner mismatch");
}
// call safeTransferFrom to transfer tokenId to msg.sender
proxy.safeTransferFrom(vaultAddress, msg.sender, tokenId);
emit CBOXClaimed(cboxWeek, msg.sender, passId, contractAddress, tokenId);
}
// management functions
function pause() public onlyOwner whenNotPaused {
_pause();
}
function unpause() public onlyOwner whenPaused {
_unpause();
}
// internal functions
function getMessageHash(
address _vaultAddress,
address _receiverAddress,
address _contractAddress,
uint256 _tokenId,
uint256 _passId,
uint256 _cboxWeek
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
_vaultAddress,
_receiverAddress,
_contractAddress,
_tokenId,
_passId,
_cboxWeek
)
);
}
function getEthSignedMessageHash(bytes32 _messageHash)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)
);
}
function verifySignature(
address _vaultAddress,
address _receiverAddress,
address _contractAddress,
uint256 _tokenId,
uint256 _passId,
uint256 _cboxWeek,
bytes memory signature
) private view returns (bool) {
bytes32 messageHash = getMessageHash(
_vaultAddress,
_receiverAddress,
_contractAddress,
_tokenId,
_passId,
_cboxWeek
);
if (_receiverAddress != msg.sender) {
revert ReceiverMismatch("This signature is not for you");
}
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == _signerAddress;
}
function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature)
private
pure
returns (address)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory sig)
private
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
if (sig.length != 65) {
revert InvalidSignature("Signature length is not 65 bytes");
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
}
}
// for calling erc721 contracts
abstract contract ERC721Proxy {
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual;
function ownerOf(uint256 tokenId) public view virtual returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | Disallow contract calls Check if cbox already claimed in given week index check if msg.sender still owns that eligible cbox | function claimToken(
address vaultAddress,
address contractAddress,
uint256 tokenId,
uint256 passId,
uint256 cboxWeek,
bytes memory signature
) public whenNotPaused {
if (msg.sender != tx.origin) {
revert PermissionError("Contract calls is not allowed");
}
if (_cboxClaims[cboxWeek][passId] == true) {
revert DuplicateEntryError("This C-BOX is already claimed");
}
verifySignature(
vaultAddress,
msg.sender,
contractAddress,
tokenId,
passId,
cboxWeek,
signature
) != true
) {
revert InvalidSignature("Signature verification failed");
}
_cboxClaims[cboxWeek][passId] = true;
ERC721Proxy coniunProxy = ERC721Proxy(_coniunContractAddress);
if (coniunProxy.ownerOf(passId) != msg.sender) {
revert ReceiverMismatch("C-BOX owner mismatch");
}
emit CBOXClaimed(cboxWeek, msg.sender, passId, contractAddress, tokenId);
}
| 1,242,142 | [
1,
1669,
5965,
6835,
4097,
2073,
309,
276,
2147,
1818,
7516,
329,
316,
864,
4860,
770,
866,
309,
1234,
18,
15330,
4859,
29065,
716,
21351,
276,
2147,
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,
225,
445,
7516,
1345,
12,
203,
565,
1758,
9229,
1887,
16,
203,
565,
1758,
6835,
1887,
16,
203,
565,
2254,
5034,
1147,
548,
16,
203,
565,
2254,
5034,
1342,
548,
16,
203,
565,
2254,
5034,
276,
2147,
6630,
16,
203,
565,
1731,
3778,
3372,
203,
225,
262,
1071,
1347,
1248,
28590,
288,
203,
565,
309,
261,
3576,
18,
15330,
480,
2229,
18,
10012,
13,
288,
203,
1377,
15226,
8509,
668,
2932,
8924,
4097,
353,
486,
2935,
8863,
203,
565,
289,
203,
203,
565,
309,
261,
67,
71,
2147,
15925,
63,
71,
2147,
6630,
6362,
5466,
548,
65,
422,
638,
13,
288,
203,
1377,
15226,
19072,
1622,
668,
2932,
2503,
385,
17,
16876,
353,
1818,
7516,
329,
8863,
203,
565,
289,
203,
203,
1377,
3929,
5374,
12,
203,
3639,
9229,
1887,
16,
203,
3639,
1234,
18,
15330,
16,
203,
3639,
6835,
1887,
16,
203,
3639,
1147,
548,
16,
203,
3639,
1342,
548,
16,
203,
3639,
276,
2147,
6630,
16,
203,
3639,
3372,
203,
1377,
262,
480,
638,
203,
565,
262,
288,
203,
1377,
15226,
1962,
5374,
2932,
5374,
11805,
2535,
8863,
203,
565,
289,
203,
203,
565,
389,
71,
2147,
15925,
63,
71,
2147,
6630,
6362,
5466,
548,
65,
273,
638,
31,
203,
203,
565,
4232,
39,
27,
5340,
3886,
356,
77,
318,
3886,
273,
4232,
39,
27,
5340,
3886,
24899,
591,
77,
318,
8924,
1887,
1769,
203,
203,
565,
309,
261,
591,
77,
318,
3886,
18,
8443,
951,
12,
5466,
548,
13,
480,
1234,
18,
15330,
13,
288,
203,
1377,
15226,
31020,
16901,
2932,
2
] |
pragma solidity ^0.5.11;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "./XPayCollectible.sol";
import "./Strings.sol";
contract XPayFactory is Ownable, ReentrancyGuard {
using Strings for string;
using SafeMath for uint256;
address public proxyRegistryAddress;
address public nftAddress;
mapping (uint256 => string) public tokenToName;
mapping (uint256 => string) public tokenToSymbol;
mapping (uint256 => uint256) public tokenToTokenID;
uint256 constant UINT256_MAX = ~uint256(0);
uint256 constant SUPPLY_PER_TOKEN_ID = UINT256_MAX;
constructor(address _proxyRegistryAddress, address _nftAddress) public {
proxyRegistryAddress = _proxyRegistryAddress;
nftAddress = _nftAddress;
}
function canMint(uint256 _tokenId, uint256 _amount) external view returns (bool) {
return _canMint(msg.sender, _tokenId, _amount);
}
function mint(uint256 _tokenId, address _toAddress, uint256 _amount, bytes calldata _data) external onlyOwner {
return _mint(_tokenId, _toAddress, _amount, _data);
}
function _mint(
uint256 _tokenId,
address _toAddress,
uint256 _amount,
bytes memory _data
) internal {
require(_canMint(msg.sender, _tokenId, _amount), "MyFactory#_mint: CANNOT_MINT_MORE");
XPayCollectible nftContract = XPayCollectible(nftAddress);
uint256 id = tokenToTokenID[_tokenId];
if (id == 0) {
id = nftContract.create(_toAddress, _amount, "", _data);
tokenToTokenID[_tokenId] = id;
} else {
nftContract.mint(_toAddress, id, _amount, _data);
}
}
function balanceOf(
address _owner,
uint256 _tokenId
) public view returns (uint256) {
if (!_isOwnerOrProxy(_owner)) {
// Only the factory owner or owner's proxy can have supply
return 0;
}
uint256 id = tokenToTokenID[_tokenId];
if (id == 0) {
// Haven't minted yet
return SUPPLY_PER_TOKEN_ID;
}
XPayCollectible nftContract = XPayCollectible(nftAddress);
uint256 currentSupply = nftContract.totalSupply(id);
return SUPPLY_PER_TOKEN_ID.sub(currentSupply);
}
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool) {
return owner() == _owner && _isOwnerOrProxy(_operator);
}
function _canMint(
address _fromAddress,
uint256 _tokenId,
uint256 _amount
) internal view returns (bool) {
return _amount > 0 && balanceOf(_fromAddress, _tokenId) >= _amount;
}
function _isOwnerOrProxy(
address _address
) internal view returns (bool) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
return owner() == _address || address(proxyRegistry.proxies(owner())) == _address;
}
}
| Only the factory owner or owner's proxy can have supply Haven't minted yet | function balanceOf(
address _owner,
uint256 _tokenId
) public view returns (uint256) {
if (!_isOwnerOrProxy(_owner)) {
return 0;
}
uint256 id = tokenToTokenID[_tokenId];
if (id == 0) {
return SUPPLY_PER_TOKEN_ID;
}
XPayCollectible nftContract = XPayCollectible(nftAddress);
uint256 currentSupply = nftContract.totalSupply(id);
return SUPPLY_PER_TOKEN_ID.sub(currentSupply);
}
| 989,506 | [
1,
3386,
326,
3272,
3410,
578,
3410,
1807,
2889,
848,
1240,
14467,
670,
7638,
1404,
312,
474,
329,
4671,
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,
225,
445,
11013,
951,
12,
203,
565,
1758,
389,
8443,
16,
203,
565,
2254,
5034,
389,
2316,
548,
203,
225,
262,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
16051,
67,
291,
5541,
1162,
3886,
24899,
8443,
3719,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
377,
203,
565,
2254,
5034,
612,
273,
1147,
774,
1345,
734,
63,
67,
2316,
548,
15533,
203,
565,
309,
261,
350,
422,
374,
13,
288,
203,
1377,
327,
16459,
23893,
67,
3194,
67,
8412,
67,
734,
31,
203,
565,
289,
203,
203,
565,
1139,
9148,
10808,
1523,
290,
1222,
8924,
273,
1139,
9148,
10808,
1523,
12,
82,
1222,
1887,
1769,
203,
565,
2254,
5034,
783,
3088,
1283,
273,
290,
1222,
8924,
18,
4963,
3088,
1283,
12,
350,
1769,
203,
565,
327,
16459,
23893,
67,
3194,
67,
8412,
67,
734,
18,
1717,
12,
2972,
3088,
1283,
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
] |
./full_match/43114/0x72960B8bf97573DaC08B3cACf8Fe86F73c4F4d85/sources/avaxArbBot.sol | path[0] is out token
| uint[] memory amounts = IUniRouter(router).getAmountsIn(a1, reversePath); | 4,628,182 | [
1,
803,
63,
20,
65,
353,
596,
1147,
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,
8526,
3778,
30980,
273,
467,
984,
77,
8259,
12,
10717,
2934,
588,
6275,
87,
382,
12,
69,
21,
16,
4219,
743,
1769,
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 ton-solidity >= 0.30.0;
import "voting_interface.sol";
contract SaverAdmin is IAdmin {
constructor() public {
require(tvm.pubkey() != 0, 101);
require(msg.pubkey() == tvm.pubkey(), 102);
tvm.accept();
reset_voter_msg_accepted();
}
modifier checkOwnerAndAccept {
require(msg.pubkey() == tvm.pubkey(), 103);
tvm.accept();
_;
}
modifier checkSenderIsVoter {
require(m_session_state.voter_map_accepted.exists(msg.sender), 104);
tvm.accept(); // TODO
_;
}
// ============================================
// Pre-initialization of the zk-SNARK keys
// ============================================
function update_crs(bytes pk, bytes vk) public checkOwnerAndAccept {
reset_context();
m_crs.pk.append(pk);
m_crs.vk.append(vk);
}
function reset_crs() public checkOwnerAndAccept {
reset_context();
m_crs.pk = hex"";
m_crs.vk = hex"";
}
// ============================================
// ============================================
// Admin has the possibility to reset history of all voting sessions
// ============================================
function reset_context() public checkOwnerAndAccept {
m_is_tally_committed = false;
m_session_state.voters_number = 0;
m_session_state.pk_eid = hex"";
m_session_state.vk_eid = hex"";
m_session_state.rt = hex"";
mapping(address => bool) m1;
m_session_state.voter_map_accepted = m1;
address[] empty_address_list;
m_session_state.voters_addresses = empty_address_list;
m_eid = hex"";
mapping(bytes => optional(bool)) m2;
mapping(bytes => optional(bool)) m3;
m_all_eid = m2;
m_all_sn = m3;
}
// ============================================
// ============================================
// Initialization of the new voting session
// ============================================
function init_voting_session(bytes eid, bytes pk_eid, bytes vk_eid, address[] voters_addresses, bytes rt) public checkOwnerAndAccept {
require(voters_addresses.length > 0, 106);
// voting session with such eid was initialized already
require(m_all_eid.add(eid, null), 107);
m_eid = eid;
SharedStructs.SessionState session_init_state;
session_init_state.pk_eid = pk_eid;
session_init_state.vk_eid = vk_eid;
session_init_state.rt = rt;
session_init_state.voters_addresses = voters_addresses;
for (uint i = 0; i < voters_addresses.length; i++) {
session_init_state.voter_map_accepted.add(voters_addresses[i], false);
}
session_init_state.voters_number = voters_addresses.length;
m_session_state = session_init_state;
m_is_tally_committed = false;
}
// ============================================
// ============================================
// Accepting and checking of the votes
// ============================================
function check_ballot(bytes eid, bytes sn) external checkSenderIsVoter responsible override returns (int32) {
m_voter_msg_accepted = 1;
int32 result_status = 0;
if (!SharedStructs.cmp_bytes(m_eid, eid)) {
// incorrect session id
m_session_state.voter_map_accepted.replace(msg.sender, false);
result_status = 1;
}
else if (!m_all_sn.add(sn, null)) {
// such sn already sent
m_session_state.voter_map_accepted.replace(msg.sender, false);
result_status = 2;
}
else {
m_session_state.voter_map_accepted.replace(msg.sender, true);
}
return result_status;
}
// ============================================
// ============================================
// Any change of the participant's vote will lead to the reset of its state
// and require another call of the check_ballot function
// ============================================
function uncommit_ballot() external checkSenderIsVoter responsible override returns (int32) {
m_voter_msg_accepted = 2;
m_session_state.voter_map_accepted.replace(msg.sender, false);
return 0;
}
// ============================================
// ============================================
// Potential problem: malicious administrator could begin tally phase before all voters committed their ballots.
// So voters would believe that everyone's votes were considered but in reality it's not the case.
// Permissibility of such possibilities depends on requirements specification for the application of the voting
// system in production (how much we trust administrator, for example, or when the possibility to hold elections
// even if several voters could be offline is needed).
// Possible solution:
// ============================================
// function is_tally_ready() private view returns(bool) {
// for ((, bool voter_status) : m_session_state.voter_map_accepted) {
// if (!voter_status) {
// return false;
// }
// }
// return true;
// }
// ============================================
// ============================================
// Final phase of the voting
// ============================================
function reset_tally() public checkOwnerAndAccept {
// See description above
// require(is_tally_ready(), 108);
m_is_tally_committed = false;
m_session_state.ct_sum = hex"";
m_session_state.m_sum = hex"";
m_session_state.dec_proof = hex"";
}
function update_tally(bytes ct_sum, bytes m_sum, bytes dec_proof) public checkOwnerAndAccept {
// See description above
// require(is_tally_ready(), 108);
m_is_tally_committed = false;
m_session_state.ct_sum.append(ct_sum);
m_session_state.m_sum.append(m_sum);
m_session_state.dec_proof.append(dec_proof);
}
function commit_tally() public checkOwnerAndAccept {
// See description above
// require(is_tally_ready(), 108);
m_is_tally_committed = true;
}
// ============================================
// ============================================
// Getters available to all participants
// ============================================
function get_crs_pk() public view returns (bytes) {
tvm.accept();
return m_crs.pk;
}
function get_crs_vk() public view returns (bytes) {
tvm.accept();
return m_crs.vk;
}
function get_voters_addresses() public view returns (address[]) {
tvm.accept();
return m_session_state.voters_addresses;
}
function get_pk_eid() public view returns (bytes) {
tvm.accept();
return m_session_state.pk_eid;
}
function get_vk_eid() public view returns (bytes) {
tvm.accept();
return m_session_state.vk_eid;
}
function get_eid() public view returns (bytes) {
tvm.accept();
return m_eid;
}
function get_rt() public view returns (bytes) {
tvm.accept();
return m_session_state.rt;
}
function get_ct_sum() public view returns (bytes) {
tvm.accept();
require(m_is_tally_committed, 110);
return m_session_state.ct_sum;
}
function get_m_sum() public view returns (bytes) {
tvm.accept();
require(m_is_tally_committed, 110);
return m_session_state.m_sum;
}
function get_dec_proof() public view returns (bytes) {
tvm.accept();
require(m_is_tally_committed, 110);
return m_session_state.dec_proof;
}
// ============================================
function get_voter_status(address voter_addr) public view checkOwnerAndAccept returns (bool) {
require(m_session_state.voter_map_accepted.exists(voter_addr), 108);
return m_session_state.voter_map_accepted.at(voter_addr);
}
function get_voters_statuses() public view checkOwnerAndAccept returns (mapping(address => bool)) {
return m_session_state.voter_map_accepted;
}
function reset_voter_msg_accepted() public checkOwnerAndAccept {
m_voter_msg_accepted = 0;
}
function get_voter_msg_accepted() public view checkOwnerAndAccept returns (uint32) {
return m_voter_msg_accepted;
}
function get_is_tally_committed() public view checkOwnerAndAccept returns (bool) {
return m_is_tally_committed;
}
bytes public m_eid;
SharedStructs.CRS public m_crs;
SharedStructs.SessionState public m_session_state;
mapping(bytes => optional(bool)) m_all_eid;
mapping(bytes => optional(bool)) m_all_sn;
uint32 m_voter_msg_accepted;
bool m_is_tally_committed;
}
| ============================================ Initialization of the new voting session ============================================ voting session with such eid was initialized already | function init_voting_session(bytes eid, bytes pk_eid, bytes vk_eid, address[] voters_addresses, bytes rt) public checkOwnerAndAccept {
require(voters_addresses.length > 0, 106);
require(m_all_eid.add(eid, null), 107);
m_eid = eid;
SharedStructs.SessionState session_init_state;
session_init_state.pk_eid = pk_eid;
session_init_state.vk_eid = vk_eid;
session_init_state.rt = rt;
session_init_state.voters_addresses = voters_addresses;
for (uint i = 0; i < voters_addresses.length; i++) {
session_init_state.voter_map_accepted.add(voters_addresses[i], false);
}
session_init_state.voters_number = voters_addresses.length;
m_session_state = session_init_state;
m_is_tally_committed = false;
}
| 14,073,664 | [
1,
4428,
14468,
26586,
434,
326,
394,
331,
17128,
1339,
422,
4428,
1432,
631,
331,
17128,
1339,
598,
4123,
22555,
1703,
6454,
1818,
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,
565,
445,
1208,
67,
90,
17128,
67,
3184,
12,
3890,
22555,
16,
1731,
2365,
67,
73,
350,
16,
1731,
331,
79,
67,
73,
350,
16,
1758,
8526,
331,
352,
414,
67,
13277,
16,
1731,
8253,
13,
1071,
866,
5541,
1876,
5933,
288,
203,
3639,
2583,
12,
90,
352,
414,
67,
13277,
18,
2469,
405,
374,
16,
1728,
26,
1769,
203,
3639,
2583,
12,
81,
67,
454,
67,
73,
350,
18,
1289,
12,
73,
350,
16,
446,
3631,
1728,
27,
1769,
203,
203,
3639,
312,
67,
73,
350,
273,
22555,
31,
203,
3639,
10314,
3823,
87,
18,
2157,
1119,
1339,
67,
2738,
67,
2019,
31,
203,
3639,
1339,
67,
2738,
67,
2019,
18,
5465,
67,
73,
350,
273,
2365,
67,
73,
350,
31,
203,
3639,
1339,
67,
2738,
67,
2019,
18,
90,
79,
67,
73,
350,
273,
331,
79,
67,
73,
350,
31,
203,
3639,
1339,
67,
2738,
67,
2019,
18,
3797,
273,
8253,
31,
203,
3639,
1339,
67,
2738,
67,
2019,
18,
90,
352,
414,
67,
13277,
273,
331,
352,
414,
67,
13277,
31,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
331,
352,
414,
67,
13277,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1339,
67,
2738,
67,
2019,
18,
90,
20005,
67,
1458,
67,
23847,
18,
1289,
12,
90,
352,
414,
67,
13277,
63,
77,
6487,
629,
1769,
203,
3639,
289,
203,
3639,
1339,
67,
2738,
67,
2019,
18,
90,
352,
414,
67,
2696,
273,
331,
352,
414,
67,
13277,
18,
2469,
31,
203,
3639,
312,
67,
3184,
67,
2
] |
// SPDX-License-Identifier: Apache License, Version 2.0
pragma solidity ^0.6.10;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { IIndexModule } from "../interfaces/IIndexModule.sol";
import { IStreamingFeeModule } from "../interfaces/IStreamingFeeModule.sol";
import { MutualUpgrade } from "../lib/MutualUpgrade.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
import { TimeLockUpgrade } from "../lib/TimeLockUpgrade.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract ICManager is TimeLockUpgrade, MutualUpgrade {
using Address for address;
using SafeMath for uint256;
using PreciseUnitMath for uint256;
/* ============ Events ============ */
event FeesAccrued(
uint256 _totalFees,
uint256 _operatorTake,
uint256 _methodologistTake
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Address of IndexModule for managing rebalances
IIndexModule public indexModule;
// Address of StreamingFeeModule
IStreamingFeeModule public feeModule;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
// Percent in 1e18 of streamingFees sent to operator
uint256 public operatorFeeSplit;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
IIndexModule _indexModule,
IStreamingFeeModule _feeModule,
address _operator,
address _methodologist,
uint256 _operatorFeeSplit
)
public
{
require(
_operatorFeeSplit <= PreciseUnitMath.preciseUnit(),
"Operator Fee Split must be less than 1e18"
);
setToken = _setToken;
indexModule = _indexModule;
feeModule = _feeModule;
operator = _operator;
methodologist = _methodologist;
operatorFeeSplit = _operatorFeeSplit;
}
/* ============ External Functions ============ */
/**
* OPERATOR ONLY: Start rebalance in IndexModule. Set new target units, zeroing out any units for components being removed from index.
* Log position multiplier to adjust target units in case fees are accrued.
*
* @param _newComponents Array of new components to add to allocation
* @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of component
* @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of component,
* if component being removed set to 0.
* @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units
* if fees accrued
*/
function startRebalance(
address[] calldata _newComponents,
uint256[] calldata _newComponentsTargetUnits,
uint256[] calldata _oldComponentsTargetUnits,
uint256 _positionMultiplier
)
external
onlyOperator
{
indexModule.startRebalance(_newComponents, _newComponentsTargetUnits, _oldComponentsTargetUnits, _positionMultiplier);
}
/**
* OPERATOR ONLY: Set trade maximums for passed components
*
* @param _components Array of components
* @param _tradeMaximums Array of trade maximums mapping to correct component
*/
function setTradeMaximums(
address[] calldata _components,
uint256[] calldata _tradeMaximums
)
external
onlyOperator
{
indexModule.setTradeMaximums(_components, _tradeMaximums);
}
/**
* OPERATOR ONLY: Set exchange for passed components
*
* @param _components Array of components
* @param _exchanges Array of exchanges mapping to correct component, uint256 used to signify exchange
*/
function setAssetExchanges(
address[] calldata _components,
uint256[] calldata _exchanges
)
external
onlyOperator
{
indexModule.setExchanges(_components, _exchanges);
}
/**
* OPERATOR ONLY: Set exchange for passed components
*
* @param _components Array of components
* @param _coolOffPeriods Array of cool off periods to correct component
*/
function setCoolOffPeriods(
address[] calldata _components,
uint256[] calldata _coolOffPeriods
)
external
onlyOperator
{
indexModule.setCoolOffPeriods(_components, _coolOffPeriods);
}
/**
* OPERATOR ONLY: Toggle ability for passed addresses to trade from current state
*
* @param _traders Array trader addresses to toggle status
* @param _statuses Booleans indicating if matching trader can trade
*/
function updateTraderStatus(
address[] calldata _traders,
bool[] calldata _statuses
)
external
onlyOperator
{
indexModule.updateTraderStatus(_traders, _statuses);
}
/**
* OPERATOR ONLY: Toggle whether anyone can trade, bypassing the traderAllowList
*
* @param _status Boolean indicating if anyone can trade
*/
function updateAnyoneTrade(bool _status) external onlyOperator {
indexModule.updateAnyoneTrade(_status);
}
/**
* Accrue fees from streaming fee module and transfer tokens to operator / methodologist addresses based on fee split
*/
function accrueFeeAndDistribute() public {
feeModule.accrueFee(setToken);
uint256 setTokenBalance = setToken.balanceOf(address(this));
uint256 operatorTake = setTokenBalance.preciseMul(operatorFeeSplit);
uint256 methodologistTake = setTokenBalance.sub(operatorTake);
setToken.transfer(operator, operatorTake);
setToken.transfer(methodologist, methodologistTake);
emit FeesAccrued(setTokenBalance, operatorTake, methodologistTake);
}
/**
* OPERATOR OR METHODOLOGIST ONLY: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function updateManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Interact with a module registered on the SetToken. Cannot be used to call functions in the
* fee module, due to ability to bypass methodologist permissions to update streaming fee.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyOperator {
require(_module != address(feeModule), "Must not be fee module");
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the streaming fee for the SetToken. Subject to timelock period agreed upon by the
* operator and methodologist
*
* @param _newFee New streaming fee percentage
*/
function updateStreamingFee(uint256 _newFee) external timeLockUpgrade onlyMethodologist {
feeModule.updateStreamingFee(setToken, _newFee);
}
/**
* OPERATOR OR METHODOLOGIST ONLY: Update the fee recipient address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newFeeRecipient New fee recipient address
*/
function updateFeeRecipient(address _newFeeRecipient) external mutualUpgrade(operator, methodologist) {
feeModule.updateFeeRecipient(setToken, _newFeeRecipient);
}
/**
* OPERATOR OR METHODOLOGIST ONLY: Update the fee split percentage. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newFeeSplit New fee split percentage
*/
function updateFeeSplit(uint256 _newFeeSplit) external mutualUpgrade(operator, methodologist) {
require(
_newFeeSplit <= PreciseUnitMath.preciseUnit(),
"Operator Fee Split must be less than 1e18"
);
// Accrue fee to operator and methodologist prior to new fee split
accrueFeeAndDistribute();
operatorFeeSplit = _newFeeSplit;
}
/**
* OPERATOR ONLY: Update the index module
*
* @param _newIndexModule New index module
*/
function updateIndexModule(IIndexModule _newIndexModule) external onlyOperator {
indexModule = _newIndexModule;
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function updateMethodologist(address _newMethodologist) external onlyMethodologist {
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function updateOperator(address _newOperator) external onlyOperator {
operator = _newOperator;
}
/**
* OPERATOR OR METHODOLOGIST ONLY: Update the timelock period for updating the streaming fee percentage.
* Operator and Methodologist must each call this function to execute the update.
*
* @param _newTimeLockPeriod New timelock period in seconds
*/
function setTimeLockPeriod(uint256 _newTimeLockPeriod) external override mutualUpgrade(operator, methodologist) {
timeLockPeriod = _newTimeLockPeriod;
}
} | * OPERATOR ONLY: Set exchange for passed components @param _components Array of components @param _exchanges Array of exchanges mapping to correct component, uint256 used to signify exchange/ | function setAssetExchanges(
address[] calldata _components,
uint256[] calldata _exchanges
)
external
onlyOperator
{
indexModule.setExchanges(_components, _exchanges);
}
| 1,010,028 | [
1,
26110,
20747,
30,
1000,
7829,
364,
2275,
4085,
225,
389,
8119,
3639,
1510,
434,
4085,
225,
389,
338,
6329,
540,
1510,
434,
431,
6329,
2874,
358,
3434,
1794,
16,
2254,
5034,
1399,
358,
1573,
1164,
7829,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
444,
6672,
424,
6329,
12,
203,
3639,
1758,
8526,
745,
892,
389,
8119,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
338,
6329,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1338,
5592,
203,
565,
288,
203,
3639,
770,
3120,
18,
542,
424,
6329,
24899,
8119,
16,
389,
338,
6329,
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
] |
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/smartowls.sol
pragma solidity ^0.8.0;
contract SmartOwlsClub is ERC721Enumerable, Ownable { //contract Name is NErdyCoderCLone and inherited from the openzaplin libraries
using Strings for uint256; //convert only uint 256 to the addresses
string public baseURI; //base url is the link of the where you hosted your metadata
string public baseExtension = ".json"; //this is add in the end of the filenumber like 1.json ,2.json
uint256 public cost = 0.06 ether; //amouont of each nft in ether if this in polygon so it also works as same but in matic (native ) token
uint256 public maxSupply = 3888; //upper capp of the maximum amount of the nft can be minted
uint256 public maxMintAmount = 30; //user can not mint more than 20 nft per session
bool public paused = false; //if we want to stop the minting it is like play and pause button
mapping(address => bool) public whitelisted; //the community member whom we want to gi9vewaway sopme nt freee os cost
constructor( //when you deply the contract first time so give this fdetails
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
mint(msg.sender, 28); //rewar6ds with the 20nft to the deployer of the contract free of cpst
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI; //returns the base url of the hosted service
}
// public
function mint(address _to, uint256 _mintAmount) public payable { // mint the nft to the this address
uint256 supply = totalSupply(); // workslike a counter *(circulation supply)
require(!paused);
require(_mintAmount > 0); //user shouldmint more than 1 nft
require(_mintAmount <= maxMintAmount); //mint amount should be less than per session minitng
require(supply + _mintAmount <= maxSupply); //counter + user minitng amount of nft should be less than upper caps of the maximum supply
if (msg.sender != owner()) { //if the caller is not the owner
if(whitelisted[msg.sender] != true) { //if the caller is notr the whitelisted
require(msg.value >= cost * _mintAmount); // check the user giving the money more than the cost of each nft * minitng nft
}
}
for (uint256 i = 1; i <= _mintAmount; i++) { //mint the nft to the caller account
_safeMint(_to, supply + i);
}
whitelisted[msg.sender] = false;
}
function walletOfOwner(address _owner) //user input the address of the other wallet and it returns the tokeid holding by the user
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) //user input the token id and it returns the url of the tokenid
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI(); //join the baseurl + tokenid + baseextension
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner //only owner can call this functions
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function whitelistUser(address _user) public onlyOwner {
whitelisted[_user] = true;
}
function removeWhitelistUser(address _user) public onlyOwner {
whitelisted[_user] = false;
}
function withdraw() public payable onlyOwner { //WITHDRAW THE AMOUNT OF THE SC COLLECTED BY THE LAZY MINTING
// This will pay 5% of the initial sale.
// You can remove this if you want, or keep it in to support HashLips and his channel.
// =============================================================================
(bool hs, ) = payable(0x73A79FEA1B3D981856369bB4E06E3D32E25751B5).call{value: address(this).balance * 5 / 100}("");
require(hs);
// =============================================================================
// This will payout the owner 95% of the contract balance.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(0x49ACDeb9652CBfCe745E5c2D39e86FEDfF89a672).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
} | if we want to stop the minting it is like play and pause button
| bool public paused = false; | 1,498,913 | [
1,
430,
732,
2545,
358,
2132,
326,
312,
474,
310,
518,
353,
3007,
6599,
471,
11722,
3568,
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,
225,
1426,
1071,
17781,
273,
629,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//
// compiler: solcjs -o ./build/contracts --optimize --abi --bin <this file>
// version: 0.4.15+commit.bbb8e64f.Emscripten.clang
//
pragma solidity ^0.4.15;
contract owned {
address public owner;
function owned() { owner = msg.sender; }
modifier onlyOwner {
if (msg.sender != owner) { revert(); }
_;
}
function changeOwner( address newowner ) onlyOwner {
owner = newowner;
}
function closedown() onlyOwner {
selfdestruct( owner );
}
}
// "extern" declare functions from token contract
interface HashBux {
function transfer(address to, uint256 value);
function balanceOf( address owner ) constant returns (uint);
}
contract HashBuxICO is owned {
uint public constant STARTTIME = 1522072800; // 26 MAR 2018 00:00 GMT
uint public constant ENDTIME = 1522764000; // 03 APR 2018 00:00 GMT
uint public constant HASHPERETH = 1000; // price: approx $0.65 ea
HashBux public tokenSC;
function HashBuxICO() {}
function setToken( address tok ) onlyOwner {
if ( tokenSC == address(0) )
tokenSC = HashBux(tok);
}
function() payable {
if (now < STARTTIME || now > ENDTIME)
revert();
// (amountinwei/weipereth * hash/eth) * ( (100 + bonuspercent)/100 )
// = amountinwei*hashpereth/weipereth*(bonus+100)/100
uint qty =
div(mul(div(mul(msg.value, HASHPERETH),1000000000000000000),(bonus()+100)),100);
if (qty > tokenSC.balanceOf(address(this)) || qty < 1)
revert();
tokenSC.transfer( msg.sender, qty );
}
// unsold tokens can be claimed by owner after sale ends
function claimUnsold() onlyOwner {
if ( now < ENDTIME )
revert();
tokenSC.transfer( owner, tokenSC.balanceOf(address(this)) );
}
function withdraw( uint amount ) onlyOwner returns (bool) {
if (amount <= this.balance)
return owner.send( amount );
return false;
}
function bonus() constant returns(uint) {
uint elapsed = now - STARTTIME;
if (elapsed < 24 hours) return 50;
if (elapsed < 48 hours) return 30;
if (elapsed < 72 hours) return 20;
if (elapsed < 96 hours) return 10;
return 0;
}
// ref:
// github.com/OpenZeppelin/zeppelin-solidity/
// blob/master/contracts/math/SafeMath.sol
function mul(uint256 a, uint256 b) constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) constant returns (uint256) {
uint256 c = a / b;
return c;
}
} | price: approx $0.65 ea
| uint public constant HASHPERETH = 1000; | 6,518,958 | [
1,
8694,
30,
10818,
271,
20,
18,
9222,
24164,
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,
225,
2254,
1071,
5381,
21641,
2500,
654,
1584,
44,
273,
4336,
31,
3639,
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/0xd4d65359c861243124A0037f4a156BD232f0474F/sources/EmartzonAirdrop.sol | loop over the users array and send the prize to each user check if the user has already claimed the prize send the prize to the user set the user as claimed add the prize amount to the total prize amount | function airdropPrizes() external onlyOwner {
for(uint i = 0; i < users.length; i++) {
if(!claimed[users[i]]) {
IERC20(prizeToken).safeTransfer(users[i], prizeAmount);
claimed[users[i]] = true;
totalPrizeAmount = totalPrizeAmount.add(prizeAmount);
}
}
}
| 16,065,917 | [
1,
6498,
1879,
326,
3677,
526,
471,
1366,
326,
846,
554,
358,
1517,
729,
866,
309,
326,
729,
711,
1818,
7516,
329,
326,
846,
554,
1366,
326,
846,
554,
358,
326,
729,
444,
326,
729,
487,
7516,
329,
527,
326,
846,
554,
3844,
358,
326,
2078,
846,
554,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
279,
6909,
1764,
2050,
3128,
1435,
3903,
1338,
5541,
288,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
3677,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
12,
5,
14784,
329,
63,
5577,
63,
77,
65,
5717,
288,
203,
7734,
467,
654,
39,
3462,
12,
683,
554,
1345,
2934,
4626,
5912,
12,
5577,
63,
77,
6487,
846,
554,
6275,
1769,
203,
7734,
7516,
329,
63,
5577,
63,
77,
13563,
273,
638,
31,
203,
7734,
2078,
2050,
554,
6275,
273,
2078,
2050,
554,
6275,
18,
1289,
12,
683,
554,
6275,
1769,
203,
5411,
289,
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
] |
pragma solidity ^0.4.13;
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() public view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId);
}
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
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;
}
}
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. This function MUST use 50,000 gas or less. Return of other
/// than the magic value MUST result in the transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _from The sending address
/// @param _tokenId The NFT identifier which is being transfered
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract LicenseAccessControl {
/**
* @notice ContractUpgrade is the event that will be emitted if we set a new contract address
*/
event ContractUpgrade(address newContract);
event Paused();
event Unpaused();
/**
* @notice CEO's address FOOBAR
*/
address public ceoAddress;
/**
* @notice CFO's address
*/
address public cfoAddress;
/**
* @notice COO's address
*/
address public cooAddress;
/**
* @notice withdrawal address
*/
address public withdrawalAddress;
bool public paused = false;
/**
* @dev Modifier to make a function only callable by the CEO
*/
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/**
* @dev Modifier to make a function only callable by the CFO
*/
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/**
* @dev Modifier to make a function only callable by the COO
*/
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/**
* @dev Modifier to make a function only callable by C-level execs
*/
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/**
* @dev Modifier to make a function only callable by CEO or CFO
*/
modifier onlyCEOOrCFO() {
require(
msg.sender == cfoAddress ||
msg.sender == ceoAddress
);
_;
}
/**
* @dev Modifier to make a function only callable by CEO or COO
*/
modifier onlyCEOOrCOO() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress
);
_;
}
/**
* @notice Sets a new CEO
* @param _newCEO - the address of the new CEO
*/
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/**
* @notice Sets a new CFO
* @param _newCFO - the address of the new CFO
*/
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/**
* @notice Sets a new COO
* @param _newCOO - the address of the new COO
*/
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/**
* @notice Sets a new withdrawalAddress
* @param _newWithdrawalAddress - the address where we'll send the funds
*/
function setWithdrawalAddress(address _newWithdrawalAddress) external onlyCEO {
require(_newWithdrawalAddress != address(0));
withdrawalAddress = _newWithdrawalAddress;
}
/**
* @notice Withdraw the balance to the withdrawalAddress
* @dev We set a withdrawal address seperate from the CFO because this allows us to withdraw to a cold wallet.
*/
function withdrawBalance() external onlyCEOOrCFO {
require(withdrawalAddress != address(0));
withdrawalAddress.transfer(this.balance);
}
/** Pausable functionality adapted from OpenZeppelin **/
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @notice called by any C-level to pause, triggers stopped state
*/
function pause() public onlyCLevel whenNotPaused {
paused = true;
Paused();
}
/**
* @notice called by the CEO to unpause, returns to normal state
*/
function unpause() public onlyCEO whenPaused {
paused = false;
Unpaused();
}
}
contract LicenseBase is LicenseAccessControl {
/**
* @notice Issued is emitted when a new license is issued
*/
event LicenseIssued(
address indexed owner,
address indexed purchaser,
uint256 licenseId,
uint256 productId,
uint256 attributes,
uint256 issuedTime,
uint256 expirationTime,
address affiliate
);
event LicenseRenewal(
address indexed owner,
address indexed purchaser,
uint256 licenseId,
uint256 productId,
uint256 expirationTime
);
struct License {
uint256 productId;
uint256 attributes;
uint256 issuedTime;
uint256 expirationTime;
address affiliate;
}
/**
* @notice All licenses in existence.
* @dev The ID of each license is an index in this array.
*/
License[] licenses;
/** internal **/
function _isValidLicense(uint256 _licenseId) internal view returns (bool) {
return licenseProductId(_licenseId) != 0;
}
/** anyone **/
/**
* @notice Get a license's productId
* @param _licenseId the license id
*/
function licenseProductId(uint256 _licenseId) public view returns (uint256) {
return licenses[_licenseId].productId;
}
/**
* @notice Get a license's attributes
* @param _licenseId the license id
*/
function licenseAttributes(uint256 _licenseId) public view returns (uint256) {
return licenses[_licenseId].attributes;
}
/**
* @notice Get a license's issueTime
* @param _licenseId the license id
*/
function licenseIssuedTime(uint256 _licenseId) public view returns (uint256) {
return licenses[_licenseId].issuedTime;
}
/**
* @notice Get a license's issueTime
* @param _licenseId the license id
*/
function licenseExpirationTime(uint256 _licenseId) public view returns (uint256) {
return licenses[_licenseId].expirationTime;
}
/**
* @notice Get a the affiliate credited for the sale of this license
* @param _licenseId the license id
*/
function licenseAffiliate(uint256 _licenseId) public view returns (address) {
return licenses[_licenseId].affiliate;
}
/**
* @notice Get a license's info
* @param _licenseId the license id
*/
function licenseInfo(uint256 _licenseId)
public view returns (uint256, uint256, uint256, uint256, address)
{
return (
licenseProductId(_licenseId),
licenseAttributes(_licenseId),
licenseIssuedTime(_licenseId),
licenseExpirationTime(_licenseId),
licenseAffiliate(_licenseId)
);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract AffiliateProgram is Pausable {
using SafeMath for uint256;
event AffiliateCredit(
// The address of the affiliate
address affiliate,
// The store's ID of what was sold (e.g. a tokenId)
uint256 productId,
// The amount owed this affiliate in this sale
uint256 amount
);
event Withdraw(address affiliate, address to, uint256 amount);
event Whitelisted(address affiliate, uint256 amount);
event RateChanged(uint256 rate, uint256 amount);
// @notice A mapping from affiliate address to their balance
mapping (address => uint256) public balances;
// @notice A mapping from affiliate address to the time of last deposit
mapping (address => uint256) public lastDepositTimes;
// @notice The last deposit globally
uint256 public lastDepositTime;
// @notice The maximum rate for any affiliate
// @dev The hard-coded maximum affiliate rate (in basis points)
// All rates are measured in basis points (1/100 of a percent)
// Values 0-10,000 map to 0%-100%
uint256 private constant hardCodedMaximumRate = 5000;
// @notice The commission exiration time
// @dev Affiliate commissions expire if they are unclaimed after this amount of time
uint256 private constant commissionExpiryTime = 30 days;
// @notice The baseline affiliate rate (in basis points) for non-whitelisted referrals
uint256 public baselineRate = 0;
// @notice A mapping from whitelisted referrals to their individual rates
mapping (address => uint256) public whitelistRates;
// @notice The maximum rate for any affiliate
// @dev overrides individual rates. This can be used to clip the rate used in bulk, if necessary
uint256 public maximumRate = 5000;
// @notice The address of the store selling products
address public storeAddress;
// @notice The contract is retired
// @dev If we decide to retire this program, this value will be set to true
// and then the contract cannot be unpaused
bool public retired = false;
/**
* @dev Modifier to make a function only callable by the store or the owner
*/
modifier onlyStoreOrOwner() {
require(
msg.sender == storeAddress ||
msg.sender == owner);
_;
}
/**
* @dev AffiliateProgram constructor - keeps the address of it's parent store
* and pauses the contract
*/
function AffiliateProgram(address _storeAddress) public {
require(_storeAddress != address(0));
storeAddress = _storeAddress;
paused = true;
}
/**
* @notice Exposes that this contract thinks it is an AffiliateProgram
*/
function isAffiliateProgram() public pure returns (bool) {
return true;
}
/**
* @notice returns the commission rate for a sale
*
* @dev rateFor returns the rate which should be used to calculate the comission
* for this affiliate/sale combination, in basis points (1/100th of a percent).
*
* We may want to completely blacklist a particular address (e.g. a known bad actor affilite).
* To that end, if the whitelistRate is exactly 1bp, we use that as a signal for blacklisting
* and return a rate of zero. The upside is that we can completely turn off
* sending transactions to a particular address when this is needed. The
* downside is that you can't issued 1/100th of a percent commission.
* However, since this is such a small amount its an acceptable tradeoff.
*
* This implementation does not use the _productId, _pruchaseId,
* _purchaseAmount, but we include them here as part of the protocol, because
* they could be useful in more advanced affiliate programs.
*
* @param _affiliate - the address of the affiliate to check for
*/
function rateFor(
address _affiliate,
uint256 /*_productId*/,
uint256 /*_purchaseId*/,
uint256 /*_purchaseAmount*/)
public
view
returns (uint256)
{
uint256 whitelistedRate = whitelistRates[_affiliate];
if(whitelistedRate > 0) {
// use 1 bp as a blacklist signal
if(whitelistedRate == 1) {
return 0;
} else {
return Math.min256(whitelistedRate, maximumRate);
}
} else {
return Math.min256(baselineRate, maximumRate);
}
}
/**
* @notice cutFor returns the affiliate cut for a sale
* @dev cutFor returns the cut (amount in wei) to give in comission to the affiliate
*
* @param _affiliate - the address of the affiliate to check for
* @param _productId - the productId in the sale
* @param _purchaseId - the purchaseId in the sale
* @param _purchaseAmount - the purchaseAmount
*/
function cutFor(
address _affiliate,
uint256 _productId,
uint256 _purchaseId,
uint256 _purchaseAmount)
public
view
returns (uint256)
{
uint256 rate = rateFor(
_affiliate,
_productId,
_purchaseId,
_purchaseAmount);
require(rate <= hardCodedMaximumRate);
return (_purchaseAmount.mul(rate)).div(10000);
}
/**
* @notice credit an affiliate for a purchase
* @dev credit accepts eth and credits the affiliate's balance for the amount
*
* @param _affiliate - the address of the affiliate to credit
* @param _purchaseId - the purchaseId of the sale
*/
function credit(
address _affiliate,
uint256 _purchaseId)
public
onlyStoreOrOwner
whenNotPaused
payable
{
require(msg.value > 0);
require(_affiliate != address(0));
balances[_affiliate] += msg.value;
lastDepositTimes[_affiliate] = now; // solium-disable-line security/no-block-members
lastDepositTime = now; // solium-disable-line security/no-block-members
AffiliateCredit(_affiliate, _purchaseId, msg.value);
}
/**
* @dev _performWithdraw performs a withdrawal from address _from and
* transfers it to _to. This can be different because we allow the owner
* to withdraw unclaimed funds after a period of time.
*
* @param _from - the address to subtract balance from
* @param _to - the address to transfer ETH to
*/
function _performWithdraw(address _from, address _to) private {
require(balances[_from] > 0);
uint256 balanceValue = balances[_from];
balances[_from] = 0;
_to.transfer(balanceValue);
Withdraw(_from, _to, balanceValue);
}
/**
* @notice withdraw
* @dev withdraw the msg.sender's balance
*/
function withdraw() public whenNotPaused {
_performWithdraw(msg.sender, msg.sender);
}
/**
* @notice withdraw from a specific account
* @dev withdrawFrom allows the owner to withdraw an affiliate's unclaimed
* ETH, after the alotted time.
*
* This function can be called even if the contract is paused
*
* @param _affiliate - the address of the affiliate
* @param _to - the address to send ETH to
*/
function withdrawFrom(address _affiliate, address _to) onlyOwner public {
// solium-disable-next-line security/no-block-members
require(now > lastDepositTimes[_affiliate].add(commissionExpiryTime));
_performWithdraw(_affiliate, _to);
}
/**
* @notice retire the contract (dangerous)
* @dev retire - withdraws the entire balance and marks the contract as retired, which
* prevents unpausing.
*
* If no new comissions have been deposited for the alotted time,
* then the owner may pause the program and retire this contract.
* This may only be performed once as the contract cannot be unpaused.
*
* We do this as an alternative to selfdestruct, because certain operations
* can still be performed after the contract has been selfdestructed, such as
* the owner withdrawing ETH accidentally sent here.
*/
function retire(address _to) onlyOwner whenPaused public {
// solium-disable-next-line security/no-block-members
require(now > lastDepositTime.add(commissionExpiryTime));
_to.transfer(this.balance);
retired = true;
}
/**
* @notice whitelist an affiliate address
* @dev whitelist - white listed affiliates can receive a different
* rate than the general public (whitelisted accounts would generally get a
* better rate).
* @param _affiliate - the affiliate address to whitelist
* @param _rate - the rate, in basis-points (1/100th of a percent) to give this affiliate in each sale. NOTE: a rate of exactly 1 is the signal to blacklist this affiliate. That is, a rate of 1 will set the commission to 0.
*/
function whitelist(address _affiliate, uint256 _rate) onlyOwner public {
require(_rate <= hardCodedMaximumRate);
whitelistRates[_affiliate] = _rate;
Whitelisted(_affiliate, _rate);
}
/**
* @notice set the rate for non-whitelisted affiliates
* @dev setBaselineRate - sets the baseline rate for any affiliate that is not whitelisted
* @param _newRate - the rate, in bp (1/100th of a percent) to give any non-whitelisted affiliate. Set to zero to "turn off"
*/
function setBaselineRate(uint256 _newRate) onlyOwner public {
require(_newRate <= hardCodedMaximumRate);
baselineRate = _newRate;
RateChanged(0, _newRate);
}
/**
* @notice set the maximum rate for any affiliate
* @dev setMaximumRate - Set the maximum rate for any affiliate, including whitelists. That is, this overrides individual rates.
* @param _newRate - the rate, in bp (1/100th of a percent)
*/
function setMaximumRate(uint256 _newRate) onlyOwner public {
require(_newRate <= hardCodedMaximumRate);
maximumRate = _newRate;
RateChanged(1, _newRate);
}
/**
* @notice unpause the contract
* @dev called by the owner to unpause, returns to normal state. Will not
* unpause if the contract is retired.
*/
function unpause() onlyOwner whenPaused public {
require(!retired);
paused = false;
Unpause();
}
}
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) external;
function setApprovalForAll(address _to, bool _approved) external;
function getApproved(uint256 _tokenId) public view returns (address);
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
}
contract LicenseInventory is LicenseBase {
using SafeMath for uint256;
event ProductCreated(
uint256 id,
uint256 price,
uint256 available,
uint256 supply,
uint256 interval,
bool renewable
);
event ProductInventoryAdjusted(uint256 productId, uint256 available);
event ProductPriceChanged(uint256 productId, uint256 price);
event ProductRenewableChanged(uint256 productId, bool renewable);
/**
* @notice Product defines a product
* * renewable: There may come a time when we which to disable the ability to renew a subscription. For example, a plan we no longer wish to support. Obviously care needs to be taken with how we communicate this to customers, but contract-wise, we want to support the ability to discontinue renewal of certain plans.
*/
struct Product {
uint256 id;
uint256 price;
uint256 available;
uint256 supply;
uint256 sold;
uint256 interval;
bool renewable;
}
// @notice All products in existence
uint256[] public allProductIds;
// @notice A mapping from product ids to Products
mapping (uint256 => Product) public products;
/*** internal ***/
/**
* @notice _productExists checks to see if a product exists
*/
function _productExists(uint256 _productId) internal view returns (bool) {
return products[_productId].id != 0;
}
function _productDoesNotExist(uint256 _productId) internal view returns (bool) {
return products[_productId].id == 0;
}
function _createProduct(
uint256 _productId,
uint256 _initialPrice,
uint256 _initialInventoryQuantity,
uint256 _supply,
uint256 _interval)
internal
{
require(_productDoesNotExist(_productId));
require(_initialInventoryQuantity <= _supply);
Product memory _product = Product({
id: _productId,
price: _initialPrice,
available: _initialInventoryQuantity,
supply: _supply,
sold: 0,
interval: _interval,
renewable: _interval == 0 ? false : true
});
products[_productId] = _product;
allProductIds.push(_productId);
ProductCreated(
_product.id,
_product.price,
_product.available,
_product.supply,
_product.interval,
_product.renewable
);
}
function _incrementInventory(
uint256 _productId,
uint256 _inventoryAdjustment)
internal
{
require(_productExists(_productId));
uint256 newInventoryLevel = products[_productId].available.add(_inventoryAdjustment);
// A supply of "0" means "unlimited". Otherwise we need to ensure that we're not over-creating this product
if(products[_productId].supply > 0) {
// you have to take already sold into account
require(products[_productId].sold.add(newInventoryLevel) <= products[_productId].supply);
}
products[_productId].available = newInventoryLevel;
}
function _decrementInventory(
uint256 _productId,
uint256 _inventoryAdjustment)
internal
{
require(_productExists(_productId));
uint256 newInventoryLevel = products[_productId].available.sub(_inventoryAdjustment);
// unnecessary because we're using SafeMath and an unsigned int
// require(newInventoryLevel >= 0);
products[_productId].available = newInventoryLevel;
}
function _clearInventory(uint256 _productId) internal
{
require(_productExists(_productId));
products[_productId].available = 0;
}
function _setPrice(uint256 _productId, uint256 _price) internal
{
require(_productExists(_productId));
products[_productId].price = _price;
}
function _setRenewable(uint256 _productId, bool _isRenewable) internal
{
require(_productExists(_productId));
products[_productId].renewable = _isRenewable;
}
function _purchaseOneUnitInStock(uint256 _productId) internal {
require(_productExists(_productId));
require(availableInventoryOf(_productId) > 0);
// lower inventory
_decrementInventory(_productId, 1);
// record that one was sold
products[_productId].sold = products[_productId].sold.add(1);
}
function _requireRenewableProduct(uint256 _productId) internal view {
// productId must exist
require(_productId != 0);
// You can only renew a subscription product
require(isSubscriptionProduct(_productId));
// The product must currently be renewable
require(renewableOf(_productId));
}
/*** public ***/
/** executives-only **/
/**
* @notice createProduct creates a new product in the system
* @param _productId - the id of the product to use (cannot be changed)
* @param _initialPrice - the starting price (price can be changed)
* @param _initialInventoryQuantity - the initial inventory (inventory can be changed)
* @param _supply - the total supply - use `0` for "unlimited" (cannot be changed)
*/
function createProduct(
uint256 _productId,
uint256 _initialPrice,
uint256 _initialInventoryQuantity,
uint256 _supply,
uint256 _interval)
external
onlyCEOOrCOO
{
_createProduct(
_productId,
_initialPrice,
_initialInventoryQuantity,
_supply,
_interval);
}
/**
* @notice incrementInventory - increments the inventory of a product
* @param _productId - the product id
* @param _inventoryAdjustment - the amount to increment
*/
function incrementInventory(
uint256 _productId,
uint256 _inventoryAdjustment)
external
onlyCLevel
{
_incrementInventory(_productId, _inventoryAdjustment);
ProductInventoryAdjusted(_productId, availableInventoryOf(_productId));
}
/**
* @notice decrementInventory removes inventory levels for a product
* @param _productId - the product id
* @param _inventoryAdjustment - the amount to decrement
*/
function decrementInventory(
uint256 _productId,
uint256 _inventoryAdjustment)
external
onlyCLevel
{
_decrementInventory(_productId, _inventoryAdjustment);
ProductInventoryAdjusted(_productId, availableInventoryOf(_productId));
}
/**
* @notice clearInventory clears the inventory of a product.
* @dev decrementInventory verifies inventory levels, whereas this method
* simply sets the inventory to zero. This is useful, for example, if an
* executive wants to take a product off the market quickly. There could be a
* race condition with decrementInventory where a product is sold, which could
* cause the admins decrement to fail (because it may try to decrement more
* than available).
*
* @param _productId - the product id
*/
function clearInventory(uint256 _productId)
external
onlyCLevel
{
_clearInventory(_productId);
ProductInventoryAdjusted(_productId, availableInventoryOf(_productId));
}
/**
* @notice setPrice - sets the price of a product
* @param _productId - the product id
* @param _price - the product price
*/
function setPrice(uint256 _productId, uint256 _price)
external
onlyCLevel
{
_setPrice(_productId, _price);
ProductPriceChanged(_productId, _price);
}
/**
* @notice setRenewable - sets if a product is renewable
* @param _productId - the product id
* @param _newRenewable - the new renewable setting
*/
function setRenewable(uint256 _productId, bool _newRenewable)
external
onlyCLevel
{
_setRenewable(_productId, _newRenewable);
ProductRenewableChanged(_productId, _newRenewable);
}
/** anyone **/
/**
* @notice The price of a product
* @param _productId - the product id
*/
function priceOf(uint256 _productId) public view returns (uint256) {
return products[_productId].price;
}
/**
* @notice The available inventory of a product
* @param _productId - the product id
*/
function availableInventoryOf(uint256 _productId) public view returns (uint256) {
return products[_productId].available;
}
/**
* @notice The total supply of a product
* @param _productId - the product id
*/
function totalSupplyOf(uint256 _productId) public view returns (uint256) {
return products[_productId].supply;
}
/**
* @notice The total sold of a product
* @param _productId - the product id
*/
function totalSold(uint256 _productId) public view returns (uint256) {
return products[_productId].sold;
}
/**
* @notice The renewal interval of a product in seconds
* @param _productId - the product id
*/
function intervalOf(uint256 _productId) public view returns (uint256) {
return products[_productId].interval;
}
/**
* @notice Is this product renewable?
* @param _productId - the product id
*/
function renewableOf(uint256 _productId) public view returns (bool) {
return products[_productId].renewable;
}
/**
* @notice The product info for a product
* @param _productId - the product id
*/
function productInfo(uint256 _productId)
public
view
returns (uint256, uint256, uint256, uint256, bool)
{
return (
priceOf(_productId),
availableInventoryOf(_productId),
totalSupplyOf(_productId),
intervalOf(_productId),
renewableOf(_productId));
}
/**
* @notice Get all product ids
*/
function getAllProductIds() public view returns (uint256[]) {
return allProductIds;
}
/**
* @notice returns the total cost to renew a product for a number of cycles
* @dev If a product is a subscription, the interval defines the period of
* time, in seconds, users can subscribe for. E.g. 1 month or 1 year.
* _numCycles is the number of these intervals we want to use in the
* calculation of the price.
*
* We require that the end user send precisely the amount required (instead
* of dealing with excess refunds). This method is public so that clients can
* read the exact amount our contract expects to receive.
*
* @param _productId - the product we're calculating for
* @param _numCycles - the number of cycles to calculate for
*/
function costForProductCycles(uint256 _productId, uint256 _numCycles)
public
view
returns (uint256)
{
return priceOf(_productId).mul(_numCycles);
}
/**
* @notice returns if this product is a subscription or not
* @dev Some products are subscriptions and others are not. An interval of 0
* means the product is not a subscription
* @param _productId - the product we're checking
*/
function isSubscriptionProduct(uint256 _productId) public view returns (bool) {
return intervalOf(_productId) > 0;
}
}
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;
}
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
contract LicenseOwnership is LicenseInventory, ERC721, ERC165, ERC721Metadata, ERC721Enumerable {
using SafeMath for uint256;
// Total amount of tokens
uint256 private totalTokens;
// Mapping from token ID to owner
mapping (uint256 => address) private tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private tokenApprovals;
// Mapping from owner address to operator address to approval
mapping (address => mapping (address => bool)) private operatorApprovals;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) private ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private ownedTokensIndex;
/*** Constants ***/
// Configure these for your own deployment
string public constant NAME = "Dottabot";
string public constant SYMBOL = "DOTTA";
string public tokenMetadataBaseURI = "https://api.dottabot.com/";
/**
* @notice token's name
*/
function name() external pure returns (string) {
return NAME;
}
/**
* @notice symbols's name
*/
function symbol() external pure returns (string) {
return SYMBOL;
}
function implementsERC721() external pure returns (bool) {
return true;
}
function tokenURI(uint256 _tokenId)
external
view
returns (string infoUrl)
{
return Strings.strConcat(
tokenMetadataBaseURI,
Strings.uint2str(_tokenId));
}
function supportsInterface(
bytes4 interfaceID) // solium-disable-line dotta/underscore-function-arguments
external view returns (bool)
{
return
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == 0x5b5e139f || // ERC721Metadata
interfaceID == 0x6466353c || // ERC-721 on 3/7/2018
interfaceID == 0x780e9d63; // ERC721Enumerable
}
function setTokenMetadataBaseURI(string _newBaseURI) external onlyCEOOrCOO {
tokenMetadataBaseURI = _newBaseURI;
}
/**
* @notice Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @notice Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return totalTokens;
}
/**
* @notice Enumerate valid NFTs
* @dev Our Licenses are kept in an array and each new License-token is just
* the next element in the array. This method is required for ERC721Enumerable
* which may support more complicated storage schemes. However, in our case the
* _index is the tokenId
* @param _index A counter less than `totalSupply()`
* @return The token identifier for the `_index`th NFT
*/
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < totalSupply());
return _index;
}
/**
* @notice Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokens[_owner].length;
}
/**
* @notice Gets the list of tokens owned by a given address
* @param _owner address to query the tokens of
* @return uint256[] representing the list of tokens owned by the passed address
*/
function tokensOf(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
/**
* @notice Enumerate NFTs assigned to an owner
* @dev Throws if `_index` >= `balanceOf(_owner)` or if
* `_owner` is the zero address, representing invalid NFTs.
* @param _owner An address where we are interested in NFTs owned by them
* @param _index A counter less than `balanceOf(_owner)`
* @return The token identifier for the `_index`th NFT assigned to `_owner`,
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index)
external
view
returns (uint256 _tokenId)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @notice Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @notice Gets the approved address to take ownership of a given token ID
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved to take ownership of the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @notice Tells whether the msg.sender is approved to transfer the given token ID or not
* Checks both for specific approval and operator approval
* @param _tokenId uint256 ID of the token to query the approval of
* @return bool whether transfer by msg.sender is approved for the given token ID or not
*/
function isSenderApprovedFor(uint256 _tokenId) internal view returns (bool) {
return
ownerOf(_tokenId) == msg.sender ||
isSpecificallyApprovedFor(msg.sender, _tokenId) ||
isApprovedForAll(ownerOf(_tokenId), msg.sender);
}
/**
* @notice Tells whether the msg.sender is approved for the given token ID or not
* @param _asker address of asking for approval
* @param _tokenId uint256 ID of the token to query the approval of
* @return bool whether the msg.sender is approved for the given token ID or not
*/
function isSpecificallyApprovedFor(address _asker, uint256 _tokenId) internal view returns (bool) {
return getApproved(_tokenId) == _asker;
}
/**
* @notice Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @notice Transfers the ownership of a given token ID to another address
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transfer(address _to, uint256 _tokenId)
external
whenNotPaused
onlyOwnerOf(_tokenId)
{
_clearApprovalAndTransfer(msg.sender, _to, _tokenId);
}
/**
* @notice Approves another address to claim for the ownership of the given token ID
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId)
external
whenNotPaused
onlyOwnerOf(_tokenId)
{
address owner = ownerOf(_tokenId);
require(_to != owner);
if (getApproved(_tokenId) != 0 || _to != 0) {
tokenApprovals[_tokenId] = _to;
Approval(owner, _to, _tokenId);
}
}
/**
* @notice Enable or disable approval for a third party ("operator") to manage all your assets
* @dev Emits the ApprovalForAll event
* @param _to Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval
*/
function setApprovalForAll(address _to, bool _approved)
external
whenNotPaused
{
if(_approved) {
approveAll(_to);
} else {
disapproveAll(_to);
}
}
/**
* @notice Approves another address to claim for the ownership of any tokens owned by this account
* @param _to address to be approved for the given token ID
*/
function approveAll(address _to)
public
whenNotPaused
{
require(_to != msg.sender);
require(_to != address(0));
operatorApprovals[msg.sender][_to] = true;
ApprovalForAll(msg.sender, _to, true);
}
/**
* @notice Removes approval for another address to claim for the ownership of any
* tokens owned by this account.
* @dev Note that this only removes the operator approval and
* does not clear any independent, specific approvals of token transfers to this address
* @param _to address to be disapproved for the given token ID
*/
function disapproveAll(address _to)
public
whenNotPaused
{
require(_to != msg.sender);
delete operatorApprovals[msg.sender][_to];
ApprovalForAll(msg.sender, _to, false);
}
/**
* @notice Claims the ownership of a given token ID
* @param _tokenId uint256 ID of the token being claimed by the msg.sender
*/
function takeOwnership(uint256 _tokenId)
external
whenNotPaused
{
require(isSenderApprovedFor(_tokenId));
_clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId);
}
/**
* @notice Transfer a token owned by another address, for which the calling address has
* previously been granted transfer approval by the owner.
* @param _from The address that owns the token
* @param _to The address that will take ownership of the token. Can be any address, including the caller
* @param _tokenId The ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
require(isSenderApprovedFor(_tokenId));
require(ownerOf(_tokenId) == _from);
_clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId);
}
/**
* @notice Transfers the ownership of an NFT from one address to another address
* @dev Throws unless `msg.sender` is the current owner, an authorized
* operator, or the approved address for this NFT. Throws if `_from` is
* not the current owner. Throws if `_to` is the zero address. Throws if
* `_tokenId` is not a valid NFT. When transfer is complete, this function
* checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT
* @param _to The new owner
* @param _tokenId The NFT to transfer
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
whenNotPaused
{
require(_to != address(0));
require(_isValidLicense(_tokenId));
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)(
_from, _tokenId, _data
);
require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/*
* @notice Transfers the ownership of an NFT from one address to another address
* @dev This works identically to the other function with an extra data parameter,
* except this function just sets data to ""
* @param _from The current owner of the NFT
* @param _to The new owner
* @param _tokenId The NFT to transfer
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @notice Mint token function
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
_addToken(_to, _tokenId);
Transfer(0x0, _to, _tokenId);
}
/**
* @notice Internal function to clear current approval and transfer the ownership of a given token ID
* @param _from address which you want to send tokens from
* @param _to address which you want to transfer the token to
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal {
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from);
require(_isValidLicense(_tokenId));
_clearApproval(_from, _tokenId);
_removeToken(_from, _tokenId);
_addToken(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
/**
* @notice Internal function to clear current approval of a given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address _owner, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _owner);
tokenApprovals[_tokenId] = 0;
Approval(_owner, 0, _tokenId);
}
/**
* @notice Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addToken(address _to, uint256 _tokenId) private {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
uint256 length = balanceOf(_to);
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
totalTokens = totalTokens.add(1);
}
/**
* @notice Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
function _isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract LicenseSale is LicenseOwnership {
AffiliateProgram public affiliateProgram;
/**
* @notice We credit affiliates for renewals that occur within this time of
* original purchase. E.g. If this is set to 1 year, and someone subscribes to
* a monthly plan, the affiliate will receive credits for that whole year, as
* the user renews their plan
*/
uint256 public renewalsCreditAffiliatesFor = 1 years;
/** internal **/
function _performPurchase(
uint256 _productId,
uint256 _numCycles,
address _assignee,
uint256 _attributes,
address _affiliate)
internal returns (uint)
{
_purchaseOneUnitInStock(_productId);
return _createLicense(
_productId,
_numCycles,
_assignee,
_attributes,
_affiliate
);
}
function _createLicense(
uint256 _productId,
uint256 _numCycles,
address _assignee,
uint256 _attributes,
address _affiliate)
internal
returns (uint)
{
// You cannot create a subscription license with zero cycles
if(isSubscriptionProduct(_productId)) {
require(_numCycles != 0);
}
// Non-subscription products have an expiration time of 0, meaning "no-expiration"
uint256 expirationTime = isSubscriptionProduct(_productId) ?
now.add(intervalOf(_productId).mul(_numCycles)) : // solium-disable-line security/no-block-members
0;
License memory _license = License({
productId: _productId,
attributes: _attributes,
issuedTime: now, // solium-disable-line security/no-block-members
expirationTime: expirationTime,
affiliate: _affiliate
});
uint256 newLicenseId = licenses.push(_license) - 1; // solium-disable-line zeppelin/no-arithmetic-operations
LicenseIssued(
_assignee,
msg.sender,
newLicenseId,
_license.productId,
_license.attributes,
_license.issuedTime,
_license.expirationTime,
_license.affiliate);
_mint(_assignee, newLicenseId);
return newLicenseId;
}
function _handleAffiliate(
address _affiliate,
uint256 _productId,
uint256 _licenseId,
uint256 _purchaseAmount)
internal
{
uint256 affiliateCut = affiliateProgram.cutFor(
_affiliate,
_productId,
_licenseId,
_purchaseAmount);
if(affiliateCut > 0) {
require(affiliateCut < _purchaseAmount);
affiliateProgram.credit.value(affiliateCut)(_affiliate, _licenseId);
}
}
function _performRenewal(uint256 _tokenId, uint256 _numCycles) internal {
// You cannot renew a non-expiring license
// ... but in what scenario can this happen?
// require(licenses[_tokenId].expirationTime != 0);
uint256 productId = licenseProductId(_tokenId);
// If our expiration is in the future, renewing adds time to that future expiration
// If our expiration has passed already, then we use `now` as the base.
uint256 renewalBaseTime = Math.max256(now, licenses[_tokenId].expirationTime);
// We assume that the payment has been validated outside of this function
uint256 newExpirationTime = renewalBaseTime.add(intervalOf(productId).mul(_numCycles));
licenses[_tokenId].expirationTime = newExpirationTime;
LicenseRenewal(
ownerOf(_tokenId),
msg.sender,
_tokenId,
productId,
newExpirationTime
);
}
function _affiliateProgramIsActive() internal view returns (bool) {
return
affiliateProgram != address(0) &&
affiliateProgram.storeAddress() == address(this) &&
!affiliateProgram.paused();
}
/** executives **/
function setAffiliateProgramAddress(address _address) external onlyCEO {
AffiliateProgram candidateContract = AffiliateProgram(_address);
require(candidateContract.isAffiliateProgram());
affiliateProgram = candidateContract;
}
function setRenewalsCreditAffiliatesFor(uint256 _newTime) external onlyCEO {
renewalsCreditAffiliatesFor = _newTime;
}
function createPromotionalPurchase(
uint256 _productId,
uint256 _numCycles,
address _assignee,
uint256 _attributes
)
external
onlyCEOOrCOO
whenNotPaused
returns (uint256)
{
return _performPurchase(
_productId,
_numCycles,
_assignee,
_attributes,
address(0));
}
function createPromotionalRenewal(
uint256 _tokenId,
uint256 _numCycles
)
external
onlyCEOOrCOO
whenNotPaused
{
uint256 productId = licenseProductId(_tokenId);
_requireRenewableProduct(productId);
return _performRenewal(_tokenId, _numCycles);
}
/** anyone **/
/**
* @notice Makes a purchase of a product.
* @dev Requires that the value sent is exactly the price of the product
* @param _productId - the product to purchase
* @param _numCycles - the number of cycles being purchased. This number should be `1` for non-subscription products and the number of cycles for subscriptions.
* @param _assignee - the address to assign the purchase to (doesn't have to be msg.sender)
* @param _affiliate - the address to of the affiliate - use address(0) if none
*/
function purchase(
uint256 _productId,
uint256 _numCycles,
address _assignee,
address _affiliate
)
external
payable
whenNotPaused
returns (uint256)
{
require(_productId != 0);
require(_numCycles != 0);
require(_assignee != address(0));
// msg.value can be zero: free products are supported
// Don't bother dealing with excess payments. Ensure the price paid is
// accurate. No more, no less.
require(msg.value == costForProductCycles(_productId, _numCycles));
// Non-subscription products should send a _numCycle of 1 -- you can't buy a
// multiple quantity of a non-subscription product with this function
if(!isSubscriptionProduct(_productId)) {
require(_numCycles == 1);
}
// this can, of course, be gamed by malicious miners. But it's adequate for our application
// Feel free to add your own strategies for product attributes
// solium-disable-next-line security/no-block-members, zeppelin/no-arithmetic-operations
uint256 attributes = uint256(keccak256(block.blockhash(block.number-1)))^_productId^(uint256(_assignee));
uint256 licenseId = _performPurchase(
_productId,
_numCycles,
_assignee,
attributes,
_affiliate);
if(
priceOf(_productId) > 0 &&
_affiliate != address(0) &&
_affiliateProgramIsActive()
) {
_handleAffiliate(
_affiliate,
_productId,
licenseId,
msg.value);
}
return licenseId;
}
/**
* @notice Renews a subscription
*/
function renew(
uint256 _tokenId,
uint256 _numCycles
)
external
payable
whenNotPaused
{
require(_numCycles != 0);
require(ownerOf(_tokenId) != address(0));
uint256 productId = licenseProductId(_tokenId);
_requireRenewableProduct(productId);
// No excess payments. Ensure the price paid is exactly accurate. No more,
// no less.
uint256 renewalCost = costForProductCycles(productId, _numCycles);
require(msg.value == renewalCost);
_performRenewal(_tokenId, _numCycles);
if(
renewalCost > 0 &&
licenseAffiliate(_tokenId) != address(0) &&
_affiliateProgramIsActive() &&
licenseIssuedTime(_tokenId).add(renewalsCreditAffiliatesFor) > now
) {
_handleAffiliate(
licenseAffiliate(_tokenId),
productId,
_tokenId,
msg.value);
}
}
}
contract LicenseCore is LicenseSale {
address public newContractAddress;
function LicenseCore() public {
paused = true;
ceoAddress = msg.sender;
cooAddress = msg.sender;
cfoAddress = msg.sender;
withdrawalAddress = msg.sender;
}
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
function() external {
assert(false);
}
function unpause() public onlyCEO whenPaused {
require(newContractAddress == address(0));
super.unpause();
}
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
} | * @notice Transfers the ownership of an NFT from one address to another address @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. @param _from The current owner of the NFT @param _to The new owner @param _tokenId The NFT to transfer @param _data Additional data with no specified format, sent in call to `_to`/ | function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
whenNotPaused
{
require(_to != address(0));
require(_isValidLicense(_tokenId));
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)(
_from, _tokenId, _data
);
require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
| 478,490 | [
1,
1429,
18881,
326,
23178,
434,
392,
423,
4464,
628,
1245,
1758,
358,
4042,
1758,
225,
22435,
3308,
1375,
3576,
18,
15330,
68,
353,
326,
783,
3410,
16,
392,
10799,
3726,
16,
578,
326,
20412,
1758,
364,
333,
423,
4464,
18,
22435,
309,
1375,
67,
2080,
68,
353,
486,
326,
783,
3410,
18,
22435,
309,
1375,
67,
869,
68,
353,
326,
3634,
1758,
18,
22435,
309,
1375,
67,
2316,
548,
68,
353,
486,
279,
923,
423,
4464,
18,
5203,
7412,
353,
3912,
16,
333,
445,
4271,
309,
1375,
67,
869,
68,
353,
279,
13706,
6835,
261,
710,
963,
405,
374,
2934,
971,
1427,
16,
518,
4097,
1375,
265,
654,
39,
27,
5340,
8872,
68,
603,
1375,
67,
869,
68,
471,
1216,
309,
326,
327,
460,
353,
486,
1375,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
265,
654,
39,
27,
5340,
8872,
12,
2867,
16,
11890,
5034,
16,
3890,
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,
225,
445,
4183,
5912,
1265,
12,
203,
565,
1758,
389,
2080,
16,
203,
565,
1758,
389,
869,
16,
203,
565,
2254,
5034,
389,
2316,
548,
16,
203,
565,
1731,
389,
892,
203,
225,
262,
203,
565,
1071,
203,
565,
1347,
1248,
28590,
203,
225,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
26810,
13211,
24899,
2316,
548,
10019,
203,
565,
7412,
1265,
24899,
2080,
16,
389,
869,
16,
389,
2316,
548,
1769,
203,
565,
309,
261,
67,
291,
8924,
24899,
869,
3719,
288,
203,
1377,
1731,
24,
1147,
12952,
1064,
273,
4232,
39,
27,
5340,
1345,
12952,
24899,
869,
2934,
265,
654,
39,
27,
5340,
8872,
18,
31604,
12,
25,
2787,
21433,
203,
3639,
389,
2080,
16,
389,
2316,
548,
16,
389,
892,
203,
1377,
11272,
203,
1377,
2583,
12,
2316,
12952,
1064,
422,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
265,
654,
39,
27,
5340,
8872,
12,
2867,
16,
11890,
5034,
16,
3890,
2225,
3719,
1769,
203,
565,
289,
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
] |
./partial_match/42/0xf6B81d1CFDb8D122176c0F26db87932aB9085358/sources/ExchangeRates.sol | * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period./ xUSD is a special case and is never stale. | function rateIsStale(bytes32 currencyKey) public view returns (bool) {
if (currencyKey == "xUSD") return false;
return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now;
}
| 8,851,147 | [
1,
1564,
309,
279,
2923,
5462,
1807,
4993,
13342,
1404,
2118,
3526,
364,
7144,
2353,
326,
14067,
3879,
18,
19,
619,
3378,
40,
353,
279,
4582,
648,
471,
353,
5903,
14067,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
4993,
2520,
19155,
12,
3890,
1578,
5462,
653,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
7095,
653,
422,
315,
92,
3378,
40,
7923,
327,
629,
31,
203,
203,
3639,
327,
1142,
4727,
1891,
10694,
12,
7095,
653,
2934,
1289,
12,
5141,
19155,
5027,
13,
411,
2037,
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
] |
{{
"language": "Solidity",
"sources": {
"contracts/5/EIP1167/CloneFactory.sol": {
"content": "pragma solidity 0.5.13;\n\n/*\nThe MIT License (MIT)\n\nCopyright (c) 2018 Murray Software, LLC.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n//solhint-disable max-line-length\n//solhint-disable no-inline-assembly\n\ncontract CloneFactory {\n\n function createClone(address target) internal returns (address result) {\n bytes20 targetBytes = bytes20(target);\n assembly {\n let clone := mload(0x40)\n mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(clone, 0x14), targetBytes)\n mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n result := create(0, clone, 0x37)\n }\n }\n\n function isClone(address target, address query) internal view returns (bool result) {\n bytes20 targetBytes = bytes20(target);\n assembly {\n let clone := mload(0x40)\n mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)\n mstore(add(clone, 0xa), targetBytes)\n mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n\n let other := add(clone, 0x40)\n extcodecopy(query, other, 0, 0x2d)\n result := and(\n eq(mload(clone), mload(other)),\n eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))\n )\n }\n }\n}\n"
},
"contracts/5/Fantastic12.sol": {
"content": "pragma solidity 0.5.13;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts/cryptography/ECDSA.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./standard_bounties/StandardBountiesWrapper.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\n\ncontract Fantastic12 {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n using StandardBountiesWrapper for address;\n\n // Constants\n uint8 public constant MAX_MEMBERS = 12;\n string public constant VERSION = \"0.1.2\";\n uint256 internal constant PRECISION = 10 ** 18;\n\n // Instance variables\n mapping(address => bool) public isMember;\n mapping(address => mapping(uint256 => bool)) public hasUsedSalt; // Stores whether a salt has been used for a member\n uint8 public memberCount;\n IERC20 public DAI;\n address payable[] public issuersOrFulfillers;\n address[] public approvers;\n uint256 public withdrawLimit;\n uint256 public withdrawnToday;\n uint256 public lastWithdrawTimestamp;\n uint256 public consensusThresholdPercentage; // at least (consensusThresholdPercentage * memberCount / PRECISION) approvers are needed to execute an action\n bool public initialized;\n\n // Modifiers\n modifier onlyMember {\n require(isMember[msg.sender], \"Not member\");\n _;\n }\n\n modifier withConsensus(\n bytes4 _funcSelector,\n bytes memory _funcParams,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n ) {\n require(\n _consensusReached(\n consensusThreshold(),\n _funcSelector,\n _funcParams,\n _members,\n _signatures,\n _salts\n ), \"No consensus\");\n _;\n }\n\n modifier withUnanimity(\n bytes4 _funcSelector,\n bytes memory _funcParams,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n ) {\n require(\n _consensusReached(\n memberCount,\n _funcSelector,\n _funcParams,\n _members,\n _signatures,\n _salts\n ), \"No unanimity\");\n _;\n }\n\n // Events\n event Shout(string message);\n event Declare(string message);\n event AddMember(address newMember, uint256 tribute);\n event RageQuit(address quitter);\n event PostBounty(uint256 bountyID, uint256 reward);\n event AddBountyReward(uint256 bountyID, uint256 reward);\n event RefundBountyReward(uint256 bountyID, uint256 refundAmount);\n event ChangeBountyData(uint256 bountyID);\n event ChangeBountyDeadline(uint256 bountyID);\n event AcceptBountySubmission(uint256 bountyID, uint256 fulfillmentID);\n event PerformBountyAction(uint256 bountyID);\n event FulfillBounty(uint256 bountyID);\n event UpdateBountyFulfillment(uint256 bountyID, uint256 fulfillmentID);\n\n // Initializer\n function init(\n address _summoner,\n address _DAI_ADDR,\n uint256 _withdrawLimit,\n uint256 _consensusThresholdPercentage\n ) public {\n require(! initialized, \"Initialized\");\n require(_consensusThresholdPercentage <= PRECISION, \"Consensus threshold > 1\");\n initialized = true;\n memberCount = 1;\n DAI = IERC20(_DAI_ADDR);\n issuersOrFulfillers = new address payable[](1);\n issuersOrFulfillers[0] = address(this);\n approvers = new address[](1);\n approvers[0] = address(this);\n withdrawLimit = _withdrawLimit;\n consensusThresholdPercentage = _consensusThresholdPercentage;\n\n // Add `_summoner` as the first member\n isMember[_summoner] = true;\n }\n\n // Functions\n\n /**\n Censorship-resistant messaging\n */\n function shout(string memory _message) public onlyMember {\n emit Shout(_message);\n }\n\n function declare(\n string memory _message,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.declare.selector,\n abi.encode(_message),\n _members,\n _signatures,\n _salts\n )\n {\n emit Declare(_message);\n }\n\n /**\n Member management\n */\n\n function addMembers(\n address[] memory _newMembers,\n uint256[] memory _tributes,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.addMembers.selector,\n abi.encode(_newMembers, _tributes),\n _members,\n _signatures,\n _salts\n )\n {\n require(_newMembers.length == _tributes.length, \"_newMembers not same length as _tributes\");\n for (uint256 i = 0; i < _newMembers.length; i = i.add(1)) {\n _addMember(_newMembers[i], _tributes[i]);\n }\n }\n\n function _addMember(\n address _newMember,\n uint256 _tribute\n )\n internal\n {\n require(_newMember != address(0), \"Member cannot be zero address\");\n require(!isMember[_newMember], \"Member cannot be added twice\");\n require(memberCount < MAX_MEMBERS, \"Max member count reached\");\n\n // Receive tribute from `_newMember`\n require(DAI.transferFrom(_newMember, address(this), _tribute), \"Tribute transfer failed\");\n\n // Add `_newMember` to squad\n isMember[_newMember] = true;\n memberCount += 1;\n\n emit AddMember(_newMember, _tribute);\n }\n\n function rageQuit(address[] memory _tokens) public onlyMember {\n // Give `msg.sender` their portion of the squad funds\n uint256 withdrawAmount;\n for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {\n if (_tokens[i] == address(0)) {\n withdrawAmount = address(this).balance.div(memberCount);\n msg.sender.transfer(withdrawAmount);\n } else {\n IERC20 token = IERC20(_tokens[i]);\n withdrawAmount = token.balanceOf(address(this)).div(memberCount);\n token.safeTransfer(msg.sender, withdrawAmount);\n }\n }\n\n // Remove `msg.sender` from squad\n isMember[msg.sender] = false;\n memberCount -= 1;\n emit RageQuit(msg.sender);\n }\n\n /**\n Fund management\n */\n\n function transferDAI(\n address[] memory _dests,\n uint256[] memory _amounts,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.transferDAI.selector,\n abi.encode(_dests, _amounts),\n _members,\n _signatures,\n _salts\n )\n {\n require(_dests.length == _amounts.length, \"_dests not same length as _amounts\");\n for (uint256 i = 0; i < _dests.length; i = i.add(1)) {\n _transferDAI(_dests[i], _amounts[i]);\n }\n }\n\n function transferTokens(\n address payable[] memory _dests,\n uint256[] memory _amounts,\n address[] memory _tokens,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.transferTokens.selector,\n abi.encode(_dests, _amounts, _tokens),\n _members,\n _signatures,\n _salts\n )\n {\n require(_dests.length == _amounts.length && _dests.length == _tokens.length, \"_dests, _amounts, _tokens not of same length\");\n for (uint256 i = 0; i < _dests.length; i = i.add(1)) {\n if (_tokens[i] == address(0)) {\n _dests[i].transfer(_amounts[i]);\n } else if (_tokens[i] == address(DAI)) {\n _transferDAI(_dests[i], _amounts[i]);\n } else {\n IERC20 token = IERC20(_tokens[i]);\n token.safeTransfer(_dests[i], _amounts[i]);\n }\n }\n }\n \n function setWithdrawLimit(\n uint256 _newLimit,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withUnanimity(\n this.setWithdrawLimit.selector,\n abi.encode(_newLimit),\n _members,\n _signatures,\n _salts\n )\n {\n withdrawLimit = _newLimit;\n }\n\n /**\n Posting bounties\n */\n\n function postBounty(\n string memory _dataIPFSHash,\n uint256 _deadline,\n uint256 _reward,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.postBounty.selector,\n abi.encode(_dataIPFSHash, _deadline, _reward, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n returns (uint256 _bountyID)\n {\n return _postBounty(_dataIPFSHash, _deadline, _reward, _standardBounties, _standardBountiesVersion);\n }\n\n function _postBounty(\n string memory _dataIPFSHash,\n uint256 _deadline,\n uint256 _reward,\n address _standardBounties,\n uint256 _standardBountiesVersion\n )\n internal\n returns (uint256 _bountyID)\n {\n require(_reward > 0, \"Reward can't be 0\");\n\n // Approve DAI reward to bounties contract\n _approveDAI(_standardBounties, _reward);\n\n _bountyID = _standardBounties.issueAndContribute(\n _standardBountiesVersion,\n address(this),\n issuersOrFulfillers,\n approvers,\n _dataIPFSHash,\n _deadline,\n address(DAI),\n _reward\n );\n\n emit PostBounty(_bountyID, _reward);\n }\n\n function addBountyReward(\n uint256 _bountyID,\n uint256 _reward,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.addBountyReward.selector,\n abi.encode(_bountyID, _reward, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n // Approve DAI reward to bounties contract\n _approveDAI(_standardBounties, _reward);\n\n _standardBounties.contribute(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n _reward\n );\n\n emit AddBountyReward(_bountyID, _reward);\n }\n\n function refundBountyReward(\n uint256 _bountyID,\n uint256[] memory _contributionIDs,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.refundBountyReward.selector,\n abi.encode(_bountyID, _contributionIDs, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n uint256 beforeBalance = DAI.balanceOf(address(this));\n _standardBounties.refundMyContributions(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n _contributionIDs\n );\n\n emit RefundBountyReward(_bountyID, DAI.balanceOf(address(this)).sub(beforeBalance));\n }\n\n function changeBountyData(\n uint256 _bountyID,\n string memory _dataIPFSHash,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.changeBountyData.selector,\n abi.encode(_bountyID, _dataIPFSHash, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n _standardBounties.changeData(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n _dataIPFSHash\n );\n emit ChangeBountyData(_bountyID);\n }\n\n function changeBountyDeadline(\n uint256 _bountyID,\n uint256 _deadline,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.changeBountyDeadline.selector,\n abi.encode(_bountyID, _deadline, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n _standardBounties.changeDeadline(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n _deadline\n );\n emit ChangeBountyDeadline(_bountyID);\n }\n\n function acceptBountySubmission(\n uint256 _bountyID,\n uint256 _fulfillmentID,\n uint256[] memory _tokenAmounts,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.acceptBountySubmission.selector,\n abi.encode(_bountyID, _fulfillmentID, _tokenAmounts, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n _standardBounties.acceptFulfillment(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n _fulfillmentID,\n _tokenAmounts\n );\n emit AcceptBountySubmission(_bountyID, _fulfillmentID);\n }\n\n /**\n Working on bounties\n */\n\n function performBountyAction(\n uint256 _bountyID,\n string memory _dataIPFSHash,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.performBountyAction.selector,\n abi.encode(_bountyID, _dataIPFSHash, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n _standardBounties.performAction(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n _dataIPFSHash\n );\n emit PerformBountyAction(_bountyID);\n }\n\n function fulfillBounty(\n uint256 _bountyID,\n string memory _dataIPFSHash,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.fulfillBounty.selector,\n abi.encode(_bountyID, _dataIPFSHash, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n _standardBounties.fulfillBounty(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n issuersOrFulfillers,\n _dataIPFSHash\n );\n emit FulfillBounty(_bountyID);\n }\n\n function updateBountyFulfillment(\n uint256 _bountyID,\n uint256 _fulfillmentID,\n string memory _dataIPFSHash,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.updateBountyFulfillment.selector,\n abi.encode(_bountyID, _fulfillmentID, _dataIPFSHash, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n _updateBountyFulfillment(_bountyID, _fulfillmentID, _dataIPFSHash, _standardBounties, _standardBountiesVersion);\n }\n\n function _updateBountyFulfillment(\n uint256 _bountyID,\n uint256 _fulfillmentID,\n string memory _dataIPFSHash,\n address _standardBounties,\n uint256 _standardBountiesVersion\n )\n internal\n {\n _standardBounties.updateFulfillment(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n _fulfillmentID,\n issuersOrFulfillers,\n _dataIPFSHash\n );\n emit UpdateBountyFulfillment(_bountyID, _fulfillmentID);\n }\n\n /**\n Consensus\n */\n\n function naiveMessageHash(\n bytes4 _funcSelector,\n bytes memory _funcParams,\n uint256 _salt\n ) public view returns (bytes32) {\n // \"|END|\" is used to separate _funcParams from the rest, to prevent maliciously ambiguous signatures\n return keccak256(abi.encodeWithSelector(_funcSelector, _funcParams, \"|END|\", _salt, address(this)));\n }\n\n function consensusThreshold() public view returns (uint8) {\n uint8 blockingThresholdMemberCount = uint8(PRECISION.sub(consensusThresholdPercentage).mul(memberCount).div(PRECISION));\n return memberCount - blockingThresholdMemberCount;\n }\n\n function _consensusReached(\n uint256 _threshold,\n bytes4 _funcSelector,\n bytes memory _funcParams,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n ) internal returns (bool) {\n // Check if the number of signatures exceed the consensus threshold\n if (_members.length != _signatures.length || _members.length < _threshold) {\n return false;\n }\n // Check if each signature is valid and signed by a member\n for (uint256 i = 0; i < _members.length; i = i.add(1)) {\n address member = _members[i];\n uint256 salt = _salts[i];\n if (!isMember[member] || hasUsedSalt[member][salt]) {\n // Invalid member or salt already used\n return false;\n }\n\n bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveMessageHash(_funcSelector, _funcParams, salt));\n address recoveredAddress = ECDSA.recover(msgHash, _signatures[i]);\n if (recoveredAddress != member) {\n // Invalid signature\n return false;\n }\n\n // Signature valid, record use of salt\n hasUsedSalt[member][salt] = true;\n }\n\n return true;\n }\n\n function _timestampToDayID(uint256 _timestamp) internal pure returns (uint256) {\n return _timestamp.sub(_timestamp % 86400).div(86400);\n }\n\n // limits how much could be withdrawn each day, should be called before transfer() or approve()\n function _applyWithdrawLimit(uint256 _amount) internal {\n // check if the limit will be exceeded\n if (_timestampToDayID(now).sub(_timestampToDayID(lastWithdrawTimestamp)) >= 1) {\n // new day, don't care about existing limit\n withdrawnToday = 0;\n }\n uint256 newWithdrawnToday = withdrawnToday.add(_amount);\n require(newWithdrawnToday <= withdrawLimit, \"Withdraw limit exceeded\");\n withdrawnToday = newWithdrawnToday;\n lastWithdrawTimestamp = now;\n }\n\n function _transferDAI(address _to, uint256 _amount) internal {\n _applyWithdrawLimit(_amount);\n require(DAI.transfer(_to, _amount), \"Failed DAI transfer\");\n }\n\n function _approveDAI(address _to, uint256 _amount) internal {\n _applyWithdrawLimit(_amount);\n require(DAI.approve(_to, 0), \"Failed to clear DAI approval\");\n require(DAI.approve(_to, _amount), \"Failed to approve DAI\");\n }\n\n function() external payable {}\n}"
},
"@openzeppelin/contracts/cryptography/ECDSA.sol": {
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * (.note) This call _does not revert_ if the signature is invalid, or\n * if the signer is otherwise unable to be retrieved. In those scenarios,\n * the zero address is returned.\n *\n * (.warning) `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise)\n * be too long), and then calling `toEthSignedMessageHash` on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n // Check the signature length\n if (signature.length != 65) {\n return (address(0));\n }\n\n // Divide the signature in r, s and v variables\n bytes32 r;\n bytes32 s;\n uint8 v;\n\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n // solhint-disable-next-line no-inline-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return address(0);\n }\n\n if (v != 27 && v != 28) {\n return address(0);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n return ecrecover(hash, v, r, s);\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * replicates the behavior of the\n * [`eth_sign`](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign)\n * JSON-RPC method.\n *\n * See `recover`.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP. Does not include\n * the optional functions; to access them see `ERC20Detailed`.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a `Transfer` event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through `transferFrom`. This is\n * zero by default.\n *\n * This value changes when `approve` or `transferFrom` are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * > Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an `Approval` event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a `Transfer` event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to `approve`. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"contracts/5/standard_bounties/StandardBountiesWrapper.sol": {
"content": "pragma solidity 0.5.13;\n\nimport \"./v1/IStandardBountiesV1.sol\";\nimport \"./v2/StandardBounties.sol\";\n\nlibrary StandardBountiesWrapper {\n function issueAndContribute(\n address _standardBounties,\n uint _standardBountiesVersion,\n address payable _sender,\n address payable[] memory _issuers,\n address[] memory _approvers,\n string memory _data,\n uint _deadline,\n address _token,\n uint _depositAmount)\n internal\n returns(uint)\n {\n if (_standardBountiesVersion == 1) {\n IStandardBountiesV1 BOUNTIES = IStandardBountiesV1(_standardBounties);\n return BOUNTIES.issueAndActivateBounty(\n _sender,\n _deadline,\n _data,\n _depositAmount,\n _sender,\n true,\n _token,\n _depositAmount\n );\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n return BOUNTIES.issueAndContribute(\n _sender,\n _issuers,\n _approvers,\n _data,\n _deadline,\n _token,\n 20, // ERC20\n _depositAmount\n );\n }\n }\n\n function contribute(\n address _standardBounties,\n uint _standardBountiesVersion,\n address payable _sender,\n uint _bountyId,\n uint _amount)\n internal\n {\n if (_standardBountiesVersion == 1) {\n IStandardBountiesV1 BOUNTIES = IStandardBountiesV1(_standardBounties);\n (,,uint fulfillmentAmount,,,) = BOUNTIES.getBounty(_bountyId);\n BOUNTIES.increasePayout(\n _bountyId,\n add(fulfillmentAmount, _amount),\n _amount\n );\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n BOUNTIES.contribute(\n _sender,\n _bountyId,\n _amount\n );\n }\n }\n\n function refundMyContributions(\n address _standardBounties,\n uint _standardBountiesVersion,\n address _sender,\n uint _bountyId,\n uint[] memory _contributionIds)\n internal\n {\n if (_standardBountiesVersion == 1) {\n IStandardBountiesV1 BOUNTIES = IStandardBountiesV1(_standardBounties);\n BOUNTIES.killBounty(\n _bountyId\n );\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n BOUNTIES.refundMyContributions(\n _sender,\n _bountyId,\n _contributionIds\n );\n }\n }\n\n function changeData(\n address _standardBounties,\n uint _standardBountiesVersion,\n address _sender,\n uint _bountyId,\n string memory _data)\n internal\n {\n if (_standardBountiesVersion == 1) {\n revert(\"Can't change data of V1 bounty\");\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n BOUNTIES.changeData(\n _sender,\n _bountyId,\n 0,\n _data\n );\n }\n }\n\n function changeDeadline(\n address _standardBounties,\n uint _standardBountiesVersion,\n address _sender,\n uint _bountyId,\n uint _deadline)\n internal\n {\n if (_standardBountiesVersion == 1) {\n IStandardBountiesV1 BOUNTIES = IStandardBountiesV1(_standardBounties);\n BOUNTIES.extendDeadline(\n _bountyId,\n _deadline\n );\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n BOUNTIES.changeDeadline(\n _sender,\n _bountyId,\n 0,\n _deadline\n );\n }\n }\n\n function acceptFulfillment(\n address _standardBounties,\n uint _standardBountiesVersion,\n address _sender,\n uint _bountyId,\n uint _fulfillmentId,\n uint[] memory _tokenAmounts)\n internal\n {\n if (_standardBountiesVersion == 1) {\n IStandardBountiesV1 BOUNTIES = IStandardBountiesV1(_standardBounties);\n BOUNTIES.acceptFulfillment(\n _bountyId,\n _fulfillmentId\n );\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n BOUNTIES.acceptFulfillment(\n _sender,\n _bountyId,\n _fulfillmentId,\n 0,\n _tokenAmounts\n );\n }\n }\n\n function performAction(\n address _standardBounties,\n uint _standardBountiesVersion,\n address _sender,\n uint _bountyId,\n string memory _data)\n internal\n {\n if (_standardBountiesVersion == 1) {\n revert(\"Not supported by V1\");\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n BOUNTIES.performAction(\n _sender,\n _bountyId,\n _data\n );\n }\n }\n\n function fulfillBounty(\n address _standardBounties,\n uint _standardBountiesVersion,\n address _sender,\n uint _bountyId,\n address payable[] memory _fulfillers,\n string memory _data)\n internal\n {\n if (_standardBountiesVersion == 1) {\n IStandardBountiesV1 BOUNTIES = IStandardBountiesV1(_standardBounties);\n BOUNTIES.fulfillBounty(\n _bountyId,\n _data\n );\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n BOUNTIES.fulfillBounty(\n _sender,\n _bountyId,\n _fulfillers,\n _data\n );\n }\n }\n\n function updateFulfillment(\n address _standardBounties,\n uint _standardBountiesVersion,\n address _sender,\n uint _bountyId,\n uint _fulfillmentId,\n address payable[] memory _fulfillers,\n string memory _data)\n internal\n {\n if (_standardBountiesVersion == 1) {\n IStandardBountiesV1 BOUNTIES = IStandardBountiesV1(_standardBounties);\n BOUNTIES.updateFulfillment(\n _bountyId,\n _fulfillmentId,\n _data\n );\n } else if (_standardBountiesVersion == 2) {\n StandardBounties BOUNTIES = StandardBounties(_standardBounties);\n BOUNTIES.updateFulfillment(\n _sender,\n _bountyId,\n _fulfillmentId,\n _fulfillers,\n _data\n );\n }\n }\n\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n}"
},
"contracts/5/standard_bounties/v1/IStandardBountiesV1.sol": {
"content": "pragma solidity 0.5.13;\n\ninterface IStandardBountiesV1 {\n\n /*\n * Events\n */\n event BountyIssued(uint bountyId);\n event BountyActivated(uint bountyId, address issuer);\n event BountyFulfilled(uint bountyId, address indexed fulfiller, uint256 indexed _fulfillmentId);\n event FulfillmentUpdated(uint _bountyId, uint _fulfillmentId);\n event FulfillmentAccepted(uint bountyId, address indexed fulfiller, uint256 indexed _fulfillmentId);\n event BountyKilled(uint bountyId, address indexed issuer);\n event ContributionAdded(uint bountyId, address indexed contributor, uint256 value);\n event DeadlineExtended(uint bountyId, uint newDeadline);\n event BountyChanged(uint bountyId);\n event IssuerTransferred(uint _bountyId, address indexed _newIssuer);\n event PayoutIncreased(uint _bountyId, uint _newFulfillmentAmount);\n\n /*\n * Public functions\n */\n\n /// @dev issueBounty(): instantiates a new draft bounty\n /// @param _issuer the address of the intended issuer of the bounty\n /// @param _deadline the unix timestamp after which fulfillments will no longer be accepted\n /// @param _data the requirements of the bounty\n /// @param _fulfillmentAmount the amount of wei to be paid out for each successful fulfillment\n /// @param _arbiter the address of the arbiter who can mediate claims\n /// @param _paysTokens whether the bounty pays in tokens or in ETH\n /// @param _tokenContract the address of the contract if _paysTokens is true\n function issueBounty(\n address _issuer,\n uint _deadline,\n string calldata _data,\n uint256 _fulfillmentAmount,\n address _arbiter,\n bool _paysTokens,\n address _tokenContract\n )\n external\n returns (uint);\n\n /// @dev issueAndActivateBounty(): instantiates a new draft bounty\n /// @param _issuer the address of the intended issuer of the bounty\n /// @param _deadline the unix timestamp after which fulfillments will no longer be accepted\n /// @param _data the requirements of the bounty\n /// @param _fulfillmentAmount the amount of wei to be paid out for each successful fulfillment\n /// @param _arbiter the address of the arbiter who can mediate claims\n /// @param _paysTokens whether the bounty pays in tokens or in ETH\n /// @param _tokenContract the address of the contract if _paysTokens is true\n /// @param _value the total number of tokens being deposited upon activation\n function issueAndActivateBounty(\n address _issuer,\n uint _deadline,\n string calldata _data,\n uint256 _fulfillmentAmount,\n address _arbiter,\n bool _paysTokens,\n address _tokenContract,\n uint256 _value\n )\n external\n payable\n returns (uint);\n\n /// @dev contribute(): a function allowing anyone to contribute tokens to a\n /// bounty, as long as it is still before its deadline. Shouldn't keep\n /// them by accident (hence 'value').\n /// @param _bountyId the index of the bounty\n /// @param _value the amount being contributed in ether to prevent accidental deposits\n /// @notice Please note you funds will be at the mercy of the issuer\n /// and can be drained at any moment. Be careful!\n function contribute (uint _bountyId, uint _value)\n external\n payable;\n\n /// @notice Send funds to activate the bug bounty\n /// @dev activateBounty(): activate a bounty so it may pay out\n /// @param _bountyId the index of the bounty\n /// @param _value the amount being contributed in ether to prevent\n /// accidental deposits\n function activateBounty(uint _bountyId, uint _value)\n external\n payable;\n\n /// @dev fulfillBounty(): submit a fulfillment for the given bounty\n /// @param _bountyId the index of the bounty\n /// @param _data the data artifacts representing the fulfillment of the bounty\n function fulfillBounty(uint _bountyId, string calldata _data)\n external;\n\n /// @dev updateFulfillment(): Submit updated data for a given fulfillment\n /// @param _bountyId the index of the bounty\n /// @param _fulfillmentId the index of the fulfillment\n /// @param _data the new data being submitted\n function updateFulfillment(uint _bountyId, uint _fulfillmentId, string calldata _data)\n external;\n\n /// @dev acceptFulfillment(): accept a given fulfillment\n /// @param _bountyId the index of the bounty\n /// @param _fulfillmentId the index of the fulfillment being accepted\n function acceptFulfillment(uint _bountyId, uint _fulfillmentId)\n external;\n\n /// @dev killBounty(): drains the contract of it's remaining\n /// funds, and moves the bounty into stage 3 (dead) since it was\n /// either killed in draft stage, or never accepted any fulfillments\n /// @param _bountyId the index of the bounty\n function killBounty(uint _bountyId)\n external;\n\n /// @dev extendDeadline(): allows the issuer to add more time to the\n /// bounty, allowing it to continue accepting fulfillments\n /// @param _bountyId the index of the bounty\n /// @param _newDeadline the new deadline in timestamp format\n function extendDeadline(uint _bountyId, uint _newDeadline)\n external;\n\n /// @dev transferIssuer(): allows the issuer to transfer ownership of the\n /// bounty to some new address\n /// @param _bountyId the index of the bounty\n /// @param _newIssuer the address of the new issuer\n function transferIssuer(uint _bountyId, address _newIssuer)\n external;\n\n\n /// @dev changeBountyDeadline(): allows the issuer to change a bounty's deadline\n /// @param _bountyId the index of the bounty\n /// @param _newDeadline the new deadline for the bounty\n function changeBountyDeadline(uint _bountyId, uint _newDeadline)\n external;\n\n /// @dev changeData(): allows the issuer to change a bounty's data\n /// @param _bountyId the index of the bounty\n /// @param _newData the new requirements of the bounty\n function changeBountyData(uint _bountyId, string calldata _newData)\n external;\n\n /// @dev changeBountyfulfillmentAmount(): allows the issuer to change a bounty's fulfillment amount\n /// @param _bountyId the index of the bounty\n /// @param _newFulfillmentAmount the new fulfillment amount\n function changeBountyFulfillmentAmount(uint _bountyId, uint _newFulfillmentAmount)\n external;\n\n /// @dev changeBountyArbiter(): allows the issuer to change a bounty's arbiter\n /// @param _bountyId the index of the bounty\n /// @param _newArbiter the new address of the arbiter\n function changeBountyArbiter(uint _bountyId, address _newArbiter)\n external;\n\n /// @dev increasePayout(): allows the issuer to increase a given fulfillment\n /// amount in the active stage\n /// @param _bountyId the index of the bounty\n /// @param _newFulfillmentAmount the new fulfillment amount\n /// @param _value the value of the additional deposit being added\n function increasePayout(uint _bountyId, uint _newFulfillmentAmount, uint _value)\n external\n payable;\n\n /// @dev getFulfillment(): Returns the fulfillment at a given index\n /// @param _bountyId the index of the bounty\n /// @param _fulfillmentId the index of the fulfillment to return\n /// @return Returns a tuple for the fulfillment\n function getFulfillment(uint _bountyId, uint _fulfillmentId)\n external\n returns (bool, address, string memory);\n\n /// @dev getBounty(): Returns the details of the bounty\n /// @param _bountyId the index of the bounty\n /// @return Returns a tuple for the bounty\n function getBounty(uint _bountyId)\n external\n returns (address, uint, uint, bool, uint, uint);\n\n /// @dev getBountyArbiter(): Returns the arbiter of the bounty\n /// @param _bountyId the index of the bounty\n /// @return Returns an address for the arbiter of the bounty\n function getBountyArbiter(uint _bountyId)\n external\n returns (address);\n\n /// @dev getBountyData(): Returns the data of the bounty\n /// @param _bountyId the index of the bounty\n /// @return Returns a string calldata for the bounty data\n function getBountyData(uint _bountyId)\n external\n returns (string memory);\n\n /// @dev getBountyToken(): Returns the token contract of the bounty\n /// @param _bountyId the index of the bounty\n /// @return Returns an address for the token that the bounty uses\n function getBountyToken(uint _bountyId)\n external\n returns (address);\n\n /// @dev getNumBounties() returns the number of bounties in the registry\n /// @return Returns the number of bounties\n function getNumBounties()\n external\n returns (uint);\n\n /// @dev getNumFulfillments() returns the number of fulfillments for a given milestone\n /// @param _bountyId the index of the bounty\n /// @return Returns the number of fulfillments\n function getNumFulfillments(uint _bountyId)\n external\n returns (uint);\n}"
},
"contracts/5/standard_bounties/v2/StandardBounties.sol": {
"content": "pragma solidity 0.5.13;\npragma experimental ABIEncoderV2;\n\nimport \"./inherited/ERC20Token.sol\";\nimport \"./inherited/ERC721Basic.sol\";\n\n\n/// @title StandardBounties\n/// @dev A contract for issuing bounties on Ethereum paying in ETH, ERC20, or ERC721 tokens\n/// @author Mark Beylin <[email protected]>, Gonçalo Sá <[email protected]>, Kevin Owocki <[email protected]>, Ricardo Guilherme Schmidt (@3esmit), Matt Garnett <[email protected]>, Craig Williams <[email protected]>\ncontract StandardBounties {\n\n using SafeMath for uint256;\n\n /*\n * Structs\n */\n\n struct Bounty {\n address payable [] issuers; // An array of individuals who have complete control over the bounty, and can edit any of its parameters\n address [] approvers; // An array of individuals who are allowed to accept the fulfillments for a particular bounty\n uint deadline; // The Unix timestamp before which all submissions must be made, and after which refunds may be processed\n address token; // The address of the token associated with the bounty (should be disregarded if the tokenVersion is 0)\n uint tokenVersion; // The version of the token being used for the bounty (0 for ETH, 20 for ERC20, 721 for ERC721)\n uint balance; // The number of tokens which the bounty is able to pay out or refund\n bool hasPaidOut; // A boolean storing whether or not the bounty has paid out at least once, meaning refunds are no longer allowed\n Fulfillment [] fulfillments; // An array of Fulfillments which store the various submissions which have been made to the bounty\n Contribution [] contributions; // An array of Contributions which store the contributions which have been made to the bounty\n }\n\n struct Fulfillment {\n address payable [] fulfillers; // An array of addresses who should receive payouts for a given submission\n address submitter; // The address of the individual who submitted the fulfillment, who is able to update the submission as needed\n }\n\n struct Contribution {\n address payable contributor; // The address of the individual who contributed\n uint amount; // The amount of tokens the user contributed\n bool refunded; // A boolean storing whether or not the contribution has been refunded yet\n }\n\n /*\n * Storage\n */\n\n uint public numBounties; // An integer storing the total number of bounties in the contract\n mapping(uint => Bounty) public bounties; // A mapping of bountyIDs to bounties\n mapping (uint => mapping (uint => bool)) public tokenBalances; // A mapping of bountyIds to tokenIds to booleans, storing whether a given bounty has a given ERC721 token in its balance\n\n\n address public owner; // The address of the individual who's allowed to set the metaTxRelayer address\n address public metaTxRelayer; // The address of the meta transaction relayer whose _sender is automatically trusted for all contract calls\n\n bool public callStarted; // Ensures mutex for the entire contract\n\n /*\n * Modifiers\n */\n\n modifier callNotStarted(){\n require(!callStarted);\n callStarted = true;\n _;\n callStarted = false;\n }\n\n modifier validateBountyArrayIndex(\n uint _index)\n {\n require(_index < numBounties);\n _;\n }\n\n modifier validateContributionArrayIndex(\n uint _bountyId,\n uint _index)\n {\n require(_index < bounties[_bountyId].contributions.length);\n _;\n }\n\n modifier validateFulfillmentArrayIndex(\n uint _bountyId,\n uint _index)\n {\n require(_index < bounties[_bountyId].fulfillments.length);\n _;\n }\n\n modifier validateIssuerArrayIndex(\n uint _bountyId,\n uint _index)\n {\n require(_index < bounties[_bountyId].issuers.length);\n _;\n }\n\n modifier validateApproverArrayIndex(\n uint _bountyId,\n uint _index)\n {\n require(_index < bounties[_bountyId].approvers.length);\n _;\n }\n\n modifier onlyIssuer(\n address _sender,\n uint _bountyId,\n uint _issuerId)\n {\n require(_sender == bounties[_bountyId].issuers[_issuerId]);\n _;\n }\n\n modifier onlySubmitter(\n address _sender,\n uint _bountyId,\n uint _fulfillmentId)\n {\n require(_sender ==\n bounties[_bountyId].fulfillments[_fulfillmentId].submitter);\n _;\n }\n\n modifier onlyContributor(\n address _sender,\n uint _bountyId,\n uint _contributionId)\n {\n require(_sender ==\n bounties[_bountyId].contributions[_contributionId].contributor);\n _;\n }\n\n modifier isApprover(\n address _sender,\n uint _bountyId,\n uint _approverId)\n {\n require(_sender == bounties[_bountyId].approvers[_approverId]);\n _;\n }\n\n modifier hasNotPaid(\n uint _bountyId)\n {\n require(!bounties[_bountyId].hasPaidOut);\n _;\n }\n\n modifier hasNotRefunded(\n uint _bountyId,\n uint _contributionId)\n {\n require(!bounties[_bountyId].contributions[_contributionId].refunded);\n _;\n }\n\n modifier senderIsValid(\n address _sender)\n {\n require(msg.sender == _sender || msg.sender == metaTxRelayer);\n _;\n }\n\n /*\n * Public functions\n */\n\n constructor() public {\n // The owner of the contract is automatically designated to be the deployer of the contract\n owner = msg.sender;\n }\n\n /// @dev setMetaTxRelayer(): Sets the address of the meta transaction relayer\n /// @param _relayer the address of the relayer\n function setMetaTxRelayer(address _relayer)\n external\n {\n require(msg.sender == owner); // Checks that only the owner can call\n require(metaTxRelayer == address(0)); // Ensures the meta tx relayer can only be set once\n metaTxRelayer = _relayer;\n }\n\n /// @dev issueBounty(): creates a new bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _issuers the array of addresses who will be the issuers of the bounty\n /// @param _approvers the array of addresses who will be the approvers of the bounty\n /// @param _data the IPFS hash representing the JSON object storing the details of the bounty (see docs for schema details)\n /// @param _deadline the timestamp which will become the deadline of the bounty\n /// @param _token the address of the token which will be used for the bounty\n /// @param _tokenVersion the version of the token being used for the bounty (0 for ETH, 20 for ERC20, 721 for ERC721)\n function issueBounty(\n address payable _sender,\n address payable [] memory _issuers,\n address [] memory _approvers,\n string memory _data,\n uint _deadline,\n address _token,\n uint _tokenVersion)\n public\n senderIsValid(_sender)\n returns (uint)\n {\n require(_tokenVersion == 0 || _tokenVersion == 20 || _tokenVersion == 721); // Ensures a bounty can only be issued with a valid token version\n require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck\n\n uint bountyId = numBounties; // The next bounty's index will always equal the number of existing bounties\n\n Bounty storage newBounty = bounties[bountyId];\n newBounty.issuers = _issuers;\n newBounty.approvers = _approvers;\n newBounty.deadline = _deadline;\n newBounty.tokenVersion = _tokenVersion;\n\n if (_tokenVersion != 0) {\n newBounty.token = _token;\n }\n\n numBounties = numBounties.add(1); // Increments the number of bounties, since a new one has just been added\n\n emit BountyIssued(bountyId,\n _sender,\n _issuers,\n _approvers,\n _data, // Instead of storing the string on-chain, it is emitted within the event for easy off-chain consumption\n _deadline,\n _token,\n _tokenVersion);\n\n return (bountyId);\n }\n\n /// @param _depositAmount the amount of tokens being deposited to the bounty, which will create a new contribution to the bounty\n\n\n function issueAndContribute(\n address payable _sender,\n address payable [] memory _issuers,\n address [] memory _approvers,\n string memory _data,\n uint _deadline,\n address _token,\n uint _tokenVersion,\n uint _depositAmount)\n public\n payable\n returns(uint)\n {\n uint bountyId = issueBounty(_sender, _issuers, _approvers, _data, _deadline, _token, _tokenVersion);\n\n contribute(_sender, bountyId, _depositAmount);\n\n return (bountyId);\n }\n\n\n /// @dev contribute(): Allows users to contribute tokens to a given bounty.\n /// Contributing merits no privelages to administer the\n /// funds in the bounty or accept submissions. Contributions\n /// are refundable but only on the condition that the deadline\n /// has elapsed, and the bounty has not yet paid out any funds.\n /// All funds deposited in a bounty are at the mercy of a\n /// bounty's issuers and approvers, so please be careful!\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _amount the amount of tokens being contributed\n function contribute(\n address payable _sender,\n uint _bountyId,\n uint _amount)\n public\n payable\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n callNotStarted\n {\n require(_amount > 0); // Contributions of 0 tokens or token ID 0 should fail\n\n bounties[_bountyId].contributions.push(\n Contribution(_sender, _amount, false)); // Adds the contribution to the bounty\n\n if (bounties[_bountyId].tokenVersion == 0){\n\n bounties[_bountyId].balance = bounties[_bountyId].balance.add(_amount); // Increments the balance of the bounty\n\n require(msg.value == _amount);\n } else if (bounties[_bountyId].tokenVersion == 20) {\n\n bounties[_bountyId].balance = bounties[_bountyId].balance.add(_amount); // Increments the balance of the bounty\n\n require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds\n require(ERC20Token(bounties[_bountyId].token).transferFrom(_sender,\n address(this),\n _amount));\n } else if (bounties[_bountyId].tokenVersion == 721) {\n tokenBalances[_bountyId][_amount] = true; // Adds the 721 token to the balance of the bounty\n\n\n require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds\n ERC721BasicToken(bounties[_bountyId].token).transferFrom(_sender,\n address(this),\n _amount);\n } else {\n revert();\n }\n\n emit ContributionAdded(_bountyId,\n bounties[_bountyId].contributions.length - 1, // The new contributionId\n _sender,\n _amount);\n }\n\n /// @dev refundContribution(): Allows users to refund the contributions they've\n /// made to a particular bounty, but only if the bounty\n /// has not yet paid out, and the deadline has elapsed.\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _contributionId the index of the contribution being refunded\n function refundContribution(\n address _sender,\n uint _bountyId,\n uint _contributionId)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateContributionArrayIndex(_bountyId, _contributionId)\n onlyContributor(_sender, _bountyId, _contributionId)\n hasNotPaid(_bountyId)\n hasNotRefunded(_bountyId, _contributionId)\n callNotStarted\n {\n require(now > bounties[_bountyId].deadline); // Refunds may only be processed after the deadline has elapsed\n\n Contribution storage contribution =\n bounties[_bountyId].contributions[_contributionId];\n\n contribution.refunded = true;\n\n transferTokens(_bountyId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor\n\n emit ContributionRefunded(_bountyId, _contributionId);\n }\n\n /// @dev refundMyContributions(): Allows users to refund their contributions in bulk\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _contributionIds the array of indexes of the contributions being refunded\n function refundMyContributions(\n address _sender,\n uint _bountyId,\n uint [] memory _contributionIds)\n public\n senderIsValid(_sender)\n {\n for (uint i = 0; i < _contributionIds.length; i++){\n refundContribution(_sender, _bountyId, _contributionIds[i]);\n }\n }\n\n /// @dev refundContributions(): Allows users to refund their contributions in bulk\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is making the call\n /// @param _contributionIds the array of indexes of the contributions being refunded\n function refundContributions(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n uint [] memory _contributionIds)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n callNotStarted\n {\n for (uint i = 0; i < _contributionIds.length; i++){\n require(_contributionIds[i] < bounties[_bountyId].contributions.length);\n\n Contribution storage contribution =\n bounties[_bountyId].contributions[_contributionIds[i]];\n\n require(!contribution.refunded);\n\n contribution.refunded = true;\n\n transferTokens(_bountyId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor\n }\n\n emit ContributionsRefunded(_bountyId, _sender, _contributionIds);\n }\n\n /// @dev drainBounty(): Allows an issuer to drain the funds from the bounty\n /// @notice when using this function, if an issuer doesn't drain the entire balance, some users may be able to refund their contributions, while others may not (which is unfair to them). Please use it wisely, only when necessary\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is making the call\n /// @param _amounts an array of amounts of tokens to be sent. The length of the array should be 1 if the bounty is in ETH or ERC20 tokens. If it's an ERC721 bounty, the array should be the list of tokenIDs.\n function drainBounty(\n address payable _sender,\n uint _bountyId,\n uint _issuerId,\n uint [] memory _amounts)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n callNotStarted\n {\n if (bounties[_bountyId].tokenVersion == 0 || bounties[_bountyId].tokenVersion == 20){\n require(_amounts.length == 1); // ensures there's only 1 amount of tokens to be returned\n require(_amounts[0] <= bounties[_bountyId].balance); // ensures an issuer doesn't try to drain the bounty of more tokens than their balance permits\n transferTokens(_bountyId, _sender, _amounts[0]); // Performs the draining of tokens to the issuer\n } else {\n for (uint i = 0; i < _amounts.length; i++){\n require(tokenBalances[_bountyId][_amounts[i]]);// ensures an issuer doesn't try to drain the bounty of a token it doesn't have in its balance\n transferTokens(_bountyId, _sender, _amounts[i]);\n }\n }\n\n emit BountyDrained(_bountyId, _sender, _amounts);\n }\n\n /// @dev performAction(): Allows users to perform any generalized action\n /// associated with a particular bounty, such as applying for it\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _data the IPFS hash corresponding to a JSON object which contains the details of the action being performed (see docs for schema details)\n function performAction(\n address _sender,\n uint _bountyId,\n string memory _data)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n {\n emit ActionPerformed(_bountyId, _sender, _data); // The _data string is emitted in an event for easy off-chain consumption\n }\n\n /// @dev fulfillBounty(): Allows users to fulfill the bounty to get paid out\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _fulfillers the array of addresses which will receive payouts for the submission\n /// @param _data the IPFS hash corresponding to a JSON object which contains the details of the submission (see docs for schema details)\n function fulfillBounty(\n address _sender,\n uint _bountyId,\n address payable [] memory _fulfillers,\n string memory _data)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n {\n require(now < bounties[_bountyId].deadline); // Submissions are only allowed to be made before the deadline\n require(_fulfillers.length > 0); // Submissions with no fulfillers would mean no one gets paid out\n\n bounties[_bountyId].fulfillments.push(Fulfillment(_fulfillers, _sender));\n\n emit BountyFulfilled(_bountyId,\n (bounties[_bountyId].fulfillments.length - 1),\n _fulfillers,\n _data, // The _data string is emitted in an event for easy off-chain consumption\n _sender);\n }\n\n /// @dev updateFulfillment(): Allows the submitter of a fulfillment to update their submission\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _fulfillmentId the index of the fulfillment\n /// @param _fulfillers the new array of addresses which will receive payouts for the submission\n /// @param _data the new IPFS hash corresponding to a JSON object which contains the details of the submission (see docs for schema details)\n function updateFulfillment(\n address _sender,\n uint _bountyId,\n uint _fulfillmentId,\n address payable [] memory _fulfillers,\n string memory _data)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateFulfillmentArrayIndex(_bountyId, _fulfillmentId)\n onlySubmitter(_sender, _bountyId, _fulfillmentId) // Only the original submitter of a fulfillment may update their submission\n {\n bounties[_bountyId].fulfillments[_fulfillmentId].fulfillers = _fulfillers;\n emit FulfillmentUpdated(_bountyId,\n _fulfillmentId,\n _fulfillers,\n _data); // The _data string is emitted in an event for easy off-chain consumption\n }\n\n /// @dev acceptFulfillment(): Allows any of the approvers to accept a given submission\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _fulfillmentId the index of the fulfillment to be accepted\n /// @param _approverId the index of the approver which is making the call\n /// @param _tokenAmounts the array of token amounts which will be paid to the\n /// fulfillers, whose length should equal the length of the\n /// _fulfillers array of the submission. If the bounty pays\n /// in ERC721 tokens, then these should be the token IDs\n /// being sent to each of the individual fulfillers\n function acceptFulfillment(\n address _sender,\n uint _bountyId,\n uint _fulfillmentId,\n uint _approverId,\n uint[] memory _tokenAmounts)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateFulfillmentArrayIndex(_bountyId, _fulfillmentId)\n isApprover(_sender, _bountyId, _approverId)\n callNotStarted\n {\n // now that the bounty has paid out at least once, refunds are no longer possible\n bounties[_bountyId].hasPaidOut = true;\n\n Fulfillment storage fulfillment =\n bounties[_bountyId].fulfillments[_fulfillmentId];\n\n require(_tokenAmounts.length == fulfillment.fulfillers.length); // Each fulfiller should get paid some amount of tokens (this can be 0)\n\n for (uint256 i = 0; i < fulfillment.fulfillers.length; i++){\n if (_tokenAmounts[i] > 0) {\n // for each fulfiller associated with the submission\n transferTokens(_bountyId, fulfillment.fulfillers[i], _tokenAmounts[i]);\n }\n }\n emit FulfillmentAccepted(_bountyId,\n _fulfillmentId,\n _sender,\n _tokenAmounts);\n }\n\n /// @dev fulfillAndAccept(): Allows any of the approvers to fulfill and accept a submission simultaneously\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _fulfillers the array of addresses which will receive payouts for the submission\n /// @param _data the IPFS hash corresponding to a JSON object which contains the details of the submission (see docs for schema details)\n /// @param _approverId the index of the approver which is making the call\n /// @param _tokenAmounts the array of token amounts which will be paid to the\n /// fulfillers, whose length should equal the length of the\n /// _fulfillers array of the submission. If the bounty pays\n /// in ERC721 tokens, then these should be the token IDs\n /// being sent to each of the individual fulfillers\n function fulfillAndAccept(\n address _sender,\n uint _bountyId,\n address payable [] memory _fulfillers,\n string memory _data,\n uint _approverId,\n uint[] memory _tokenAmounts)\n public\n senderIsValid(_sender)\n {\n // first fulfills the bounty on behalf of the fulfillers\n fulfillBounty(_sender, _bountyId, _fulfillers, _data);\n\n // then accepts the fulfillment\n acceptFulfillment(_sender,\n _bountyId,\n bounties[_bountyId].fulfillments.length - 1,\n _approverId,\n _tokenAmounts);\n }\n\n\n\n /// @dev changeBounty(): Allows any of the issuers to change the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _issuers the new array of addresses who will be the issuers of the bounty\n /// @param _approvers the new array of addresses who will be the approvers of the bounty\n /// @param _data the new IPFS hash representing the JSON object storing the details of the bounty (see docs for schema details)\n /// @param _deadline the new timestamp which will become the deadline of the bounty\n function changeBounty(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n address payable [] memory _issuers,\n address payable [] memory _approvers,\n string memory _data,\n uint _deadline)\n public\n senderIsValid(_sender)\n {\n require(_bountyId < numBounties); // makes the validateBountyArrayIndex modifier in-line to avoid stack too deep errors\n require(_issuerId < bounties[_bountyId].issuers.length); // makes the validateIssuerArrayIndex modifier in-line to avoid stack too deep errors\n require(_sender == bounties[_bountyId].issuers[_issuerId]); // makes the onlyIssuer modifier in-line to avoid stack too deep errors\n\n require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck\n\n bounties[_bountyId].issuers = _issuers;\n bounties[_bountyId].approvers = _approvers;\n bounties[_bountyId].deadline = _deadline;\n emit BountyChanged(_bountyId,\n _sender,\n _issuers,\n _approvers,\n _data,\n _deadline);\n }\n\n /// @dev changeIssuer(): Allows any of the issuers to change a particular issuer of the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _issuerIdToChange the index of the issuer who is being changed\n /// @param _newIssuer the address of the new issuer\n function changeIssuer(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n uint _issuerIdToChange,\n address payable _newIssuer)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateIssuerArrayIndex(_bountyId, _issuerIdToChange)\n onlyIssuer(_sender, _bountyId, _issuerId)\n {\n require(_issuerId < bounties[_bountyId].issuers.length || _issuerId == 0);\n\n bounties[_bountyId].issuers[_issuerIdToChange] = _newIssuer;\n\n emit BountyIssuersUpdated(_bountyId, _sender, bounties[_bountyId].issuers);\n }\n\n /// @dev changeApprover(): Allows any of the issuers to change a particular approver of the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _approverId the index of the approver who is being changed\n /// @param _approver the address of the new approver\n function changeApprover(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n uint _approverId,\n address payable _approver)\n external\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n validateApproverArrayIndex(_bountyId, _approverId)\n {\n bounties[_bountyId].approvers[_approverId] = _approver;\n\n emit BountyApproversUpdated(_bountyId, _sender, bounties[_bountyId].approvers);\n }\n\n /// @dev changeData(): Allows any of the issuers to change the data the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _data the new IPFS hash representing the JSON object storing the details of the bounty (see docs for schema details)\n function changeData(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n string memory _data)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateIssuerArrayIndex(_bountyId, _issuerId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n {\n emit BountyDataChanged(_bountyId, _sender, _data); // The new _data is emitted within an event rather than being stored on-chain for minimized gas costs\n }\n\n /// @dev changeDeadline(): Allows any of the issuers to change the deadline the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _deadline the new timestamp which will become the deadline of the bounty\n function changeDeadline(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n uint _deadline)\n external\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateIssuerArrayIndex(_bountyId, _issuerId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n {\n bounties[_bountyId].deadline = _deadline;\n\n emit BountyDeadlineChanged(_bountyId, _sender, _deadline);\n }\n\n /// @dev addIssuers(): Allows any of the issuers to add more issuers to the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _issuers the array of addresses to add to the list of valid issuers\n function addIssuers(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n address payable [] memory _issuers)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateIssuerArrayIndex(_bountyId, _issuerId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n {\n for (uint i = 0; i < _issuers.length; i++){\n bounties[_bountyId].issuers.push(_issuers[i]);\n }\n\n emit BountyIssuersUpdated(_bountyId, _sender, bounties[_bountyId].issuers);\n }\n\n /// @dev replaceIssuers(): Allows any of the issuers to replace the issuers of the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _issuers the array of addresses to replace the list of valid issuers\n function replaceIssuers(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n address payable [] memory _issuers)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateIssuerArrayIndex(_bountyId, _issuerId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n {\n require(_issuers.length > 0 || bounties[_bountyId].approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck\n\n bounties[_bountyId].issuers = _issuers;\n\n emit BountyIssuersUpdated(_bountyId, _sender, bounties[_bountyId].issuers);\n }\n\n /// @dev addApprovers(): Allows any of the issuers to add more approvers to the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _approvers the array of addresses to add to the list of valid approvers\n function addApprovers(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n address [] memory _approvers)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateIssuerArrayIndex(_bountyId, _issuerId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n {\n for (uint i = 0; i < _approvers.length; i++){\n bounties[_bountyId].approvers.push(_approvers[i]);\n }\n\n emit BountyApproversUpdated(_bountyId, _sender, bounties[_bountyId].approvers);\n }\n\n /// @dev replaceApprovers(): Allows any of the issuers to replace the approvers of the bounty\n /// @param _sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)\n /// @param _bountyId the index of the bounty\n /// @param _issuerId the index of the issuer who is calling the function\n /// @param _approvers the array of addresses to replace the list of valid approvers\n function replaceApprovers(\n address _sender,\n uint _bountyId,\n uint _issuerId,\n address [] memory _approvers)\n public\n senderIsValid(_sender)\n validateBountyArrayIndex(_bountyId)\n validateIssuerArrayIndex(_bountyId, _issuerId)\n onlyIssuer(_sender, _bountyId, _issuerId)\n {\n require(bounties[_bountyId].issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck\n bounties[_bountyId].approvers = _approvers;\n\n emit BountyApproversUpdated(_bountyId, _sender, bounties[_bountyId].approvers);\n }\n\n /// @dev getBounty(): Returns the details of the bounty\n /// @param _bountyId the index of the bounty\n /// @return Returns a tuple for the bounty\n function getBounty(uint _bountyId)\n external\n view\n returns (Bounty memory)\n {\n return bounties[_bountyId];\n }\n\n\n function transferTokens(uint _bountyId, address payable _to, uint _amount)\n internal\n {\n if (bounties[_bountyId].tokenVersion == 0){\n require(_amount > 0); // Sending 0 tokens should throw\n require(bounties[_bountyId].balance >= _amount);\n\n bounties[_bountyId].balance = bounties[_bountyId].balance.sub(_amount);\n\n _to.transfer(_amount);\n } else if (bounties[_bountyId].tokenVersion == 20) {\n require(_amount > 0); // Sending 0 tokens should throw\n require(bounties[_bountyId].balance >= _amount);\n\n bounties[_bountyId].balance = bounties[_bountyId].balance.sub(_amount);\n\n require(ERC20Token(bounties[_bountyId].token).transfer(_to, _amount));\n } else if (bounties[_bountyId].tokenVersion == 721) {\n require(tokenBalances[_bountyId][_amount]);\n\n tokenBalances[_bountyId][_amount] = false; // Removes the 721 token from the balance of the bounty\n\n ERC721BasicToken(bounties[_bountyId].token).transferFrom(address(this),\n _to,\n _amount);\n } else {\n revert();\n }\n }\n\n /*\n * Events\n */\n\n event BountyIssued(uint _bountyId, address payable _creator, address payable [] _issuers, address [] _approvers, string _data, uint _deadline, address _token, uint _tokenVersion);\n event ContributionAdded(uint _bountyId, uint _contributionId, address payable _contributor, uint _amount);\n event ContributionRefunded(uint _bountyId, uint _contributionId);\n event ContributionsRefunded(uint _bountyId, address _issuer, uint [] _contributionIds);\n event BountyDrained(uint _bountyId, address _issuer, uint [] _amounts);\n event ActionPerformed(uint _bountyId, address _fulfiller, string _data);\n event BountyFulfilled(uint _bountyId, uint _fulfillmentId, address payable [] _fulfillers, string _data, address _submitter);\n event FulfillmentUpdated(uint _bountyId, uint _fulfillmentId, address payable [] _fulfillers, string _data);\n event FulfillmentAccepted(uint _bountyId, uint _fulfillmentId, address _approver, uint[] _tokenAmounts);\n event BountyChanged(uint _bountyId, address _changer, address payable [] _issuers, address payable [] _approvers, string _data, uint _deadline);\n event BountyIssuersUpdated(uint _bountyId, address _changer, address payable [] _issuers);\n event BountyApproversUpdated(uint _bountyId, address _changer, address [] _approvers);\n event BountyDataChanged(uint _bountyId, address _changer, string _data);\n event BountyDeadlineChanged(uint _bountyId, address _changer, uint _deadline);\n}\n"
},
"contracts/5/standard_bounties/v2/inherited/ERC20Token.sol": {
"content": "/*\nYou should inherit from StandardToken or, for a token like you would want to\ndeploy in something like Mist, see HumanStandardToken.sol.\n(This implements ONLY the standard functions and NOTHING else.\nIf you deploy this, you won't have anything useful.)\n\nImplements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20\n.*/\npragma solidity 0.5.13;\n\nimport \"./Token.sol\";\n\ncontract ERC20Token is Token {\n\n function transfer(address _to, uint256 _value) public returns (bool success) {\n //Default assumes totalSupply can't be over max (2^256 - 1).\n //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.\n //Replace the if with this one instead.\n //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {\n if (balances[msg.sender] >= _value && _value > 0) {\n balances[msg.sender] -= _value;\n balances[_to] += _value;\n emit Transfer(msg.sender, _to, _value);\n return true;\n } else { return false; }\n }\n\n function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\n //same as above. Replace this line with the following if you want to protect against wrapping uints.\n //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {\n if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {\n balances[_to] += _value;\n balances[_from] -= _value;\n allowed[_from][msg.sender] -= _value;\n emit Transfer(_from, _to, _value);\n return true;\n } else { return false; }\n }\n\n function balanceOf(address _owner) view public returns (uint256 balance) {\n return balances[_owner];\n }\n\n function approve(address _spender, uint256 _value) public returns (bool success) {\n allowed[msg.sender][_spender] = _value;\n emit Approval(msg.sender, _spender, _value);\n return true;\n }\n\n function allowance(address _owner, address _spender) view public returns (uint256 remaining) {\n return allowed[_owner][_spender];\n }\n\n mapping (address => uint256) balances;\n mapping (address => mapping (address => uint256)) allowed;\n}\n"
},
"contracts/5/standard_bounties/v2/inherited/Token.sol": {
"content": "// Abstract contract for the full ERC 20 Token standard\n// https://github.com/ethereum/EIPs/issues/20\npragma solidity 0.5.13;\n\ncontract Token {\n /* This is a slight change to the ERC20 base standard.\n function totalSupply() pure returns (uint256 supply);\n is replaced with:\n uint256 public totalSupply;\n This automatically creates a getter function for the totalSupply.\n This is moved to the base contract since public getter functions are not\n currently recognised as an implementation of the matching abstract\n function by the compiler.\n */\n /// total amount of tokens\n uint256 public totalSupply;\n\n /// @param _owner The address from which the balance will be retrieved\n /// @return The balance\n function balanceOf(address _owner) view public returns (uint256 balance);\n\n /// @notice send `_value` token to `_to` from `msg.sender`\n /// @param _to The address of the recipient\n /// @param _value The amount of token to be transferred\n /// @return Whether the transfer was successful or not\n function transfer(address _to, uint256 _value) public returns (bool success);\n\n /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`\n /// @param _from The address of the sender\n /// @param _to The address of the recipient\n /// @param _value The amount of token to be transferred\n /// @return Whether the transfer was successful or not\n function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);\n\n /// @notice `msg.sender` approves `_spender` to spend `_value` tokens\n /// @param _spender The address of the account able to transfer the tokens\n /// @param _value The amount of tokens to be approved for transfer\n /// @return Whether the approval was successful or not\n function approve(address _spender, uint256 _value) public returns (bool success);\n\n /// @param _owner The address of the account owning tokens\n /// @param _spender The address of the account able to transfer the tokens\n /// @return Amount of remaining tokens allowed to spent\n function allowance(address _owner, address _spender) public view returns (uint256 remaining);\n\n event Transfer(address _from, address _to, uint256 _value);\n event Approval(address _owner, address _spender, uint256 _value);\n}\n"
},
"contracts/5/standard_bounties/v2/inherited/ERC721Basic.sol": {
"content": " pragma solidity 0.5.13;\n\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n/**\n * Utility library of inline functions on addresses\n */\nlibrary AddressUtils {\n\n /**\n * Returns whether the target address is a contract\n * @dev This function will return false if invoked during the constructor of a contract,\n * as the code is not actually created until after the constructor finishes.\n * @param addr address to check\n * @return whether the target address is a contract\n */\n function isContract(address addr) internal view returns (bool) {\n uint256 size;\n // XXX Currently there is no better way to check if there is a contract in an address\n // than to check the size of the code at that address.\n // See https://ethereum.stackexchange.com/a/14016/36603\n // for more details about how this works.\n // TODO Check this again before the Serenity release, because all addresses will be\n // contracts then.\n // solium-disable-next-line security/no-inline-assembly\n assembly { size := extcodesize(addr) }\n return size > 0;\n }\n\n}\n\n/**\n * @title ERC165\n * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md\n */\ninterface ERC165 {\n\n /**\n * @notice Query if a contract implements an interface\n * @param _interfaceId The interface identifier, as specified in ERC-165\n * @dev Interface identification is specified in ERC-165. This function\n * uses less than 30,000 gas.\n */\n function supportsInterface(bytes4 _interfaceId)\n external\n view\n returns (bool);\n}\n\n\n/**\n * @title SupportsInterfaceWithLookup\n * @author Matt Condon (@shrugs)\n * @dev Implements ERC165 using a lookup table.\n */\ncontract SupportsInterfaceWithLookup is ERC165 {\n bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;\n /**\n * 0x01ffc9a7 ===\n * bytes4(keccak256('supportsInterface(bytes4)'))\n */\n\n /**\n * @dev a mapping of interface id to whether or not it's supported\n */\n mapping(bytes4 => bool) internal supportedInterfaces;\n\n /**\n * @dev A contract implementing SupportsInterfaceWithLookup\n * implement ERC165 itself\n */\n constructor()\n public\n {\n _registerInterface(InterfaceId_ERC165);\n }\n\n /**\n * @dev implement supportsInterface(bytes4) using a lookup table\n */\n function supportsInterface(bytes4 _interfaceId)\n external\n view\n returns (bool)\n {\n return supportedInterfaces[_interfaceId];\n }\n\n /**\n * @dev private method for registering an interface\n */\n function _registerInterface(bytes4 _interfaceId)\n internal\n {\n require(_interfaceId != 0xffffffff);\n supportedInterfaces[_interfaceId] = true;\n }\n}\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ncontract ERC721Receiver {\n /**\n * @dev Magic value to be returned upon successful reception of an NFT\n * Equals to `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`,\n * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`\n */\n bytes4 internal constant ERC721_RECEIVED = 0xf0b9e5ba;\n\n /**\n * @notice Handle the receipt of an NFT\n * @dev The ERC721 smart contract calls this function on the recipient\n * after a `safetransfer`. This function MAY throw to revert and reject the\n * transfer. This function MUST use 50,000 gas or less. Return of other\n * than the magic value MUST result in the transaction being reverted.\n * Note: the contract address is always the message sender.\n * @param _from The sending address\n * @param _tokenId The NFT identifier which is being transfered\n * @param _data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`\n */\n function onERC721Received(\n address _from,\n uint256 _tokenId,\n bytes memory _data\n )\n public\n returns(bytes4);\n}\n\n/**\n * @title ERC721 Non-Fungible Token Standard basic interface\n * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md\n */\ncontract ERC721Basic is ERC165 {\n event Transfer(\n address _from,\n address _to,\n uint256 _tokenId\n );\n event Approval(\n address _owner,\n address _approved,\n uint256 _tokenId\n );\n event ApprovalForAll(\n address _owner,\n address _operator,\n bool _approved\n );\n\n function balanceOf(address _owner) public view returns (uint256 _balance);\n function ownerOf(uint256 _tokenId) public view returns (address _owner);\n function exists(uint256 _tokenId) public view returns (bool _exists);\n\n function approve(address _to, uint256 _tokenId) public;\n function getApproved(uint256 _tokenId)\n public view returns (address _operator);\n\n function setApprovalForAll(address _operator, bool _approved) public;\n function isApprovedForAll(address _owner, address _operator)\n public view returns (bool);\n\n function transferFrom(address _from, address _to, uint256 _tokenId) public;\n function safeTransferFrom(address _from, address _to, uint256 _tokenId)\n public;\n\n function safeTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId,\n bytes memory _data\n )\n public;\n}\n\n/**\n * @title ERC721 Non-Fungible Token Standard basic implementation\n * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md\n */\ncontract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {\n\n bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;\n /*\n * 0x80ac58cd ===\n * bytes4(keccak256('balanceOf(address)')) ^\n * bytes4(keccak256('ownerOf(uint256)')) ^\n * bytes4(keccak256('approve(address,uint256)')) ^\n * bytes4(keccak256('getApproved(uint256)')) ^\n * bytes4(keccak256('setApprovalForAll(address,bool)')) ^\n * bytes4(keccak256('isApprovedForAll(address,address)')) ^\n * bytes4(keccak256('transferFrom(address,address,uint256)')) ^\n * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^\n * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))\n */\n\n bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;\n /*\n * 0x4f558e79 ===\n * bytes4(keccak256('exists(uint256)'))\n */\n\n using SafeMath for uint256;\n using AddressUtils for address;\n\n // Equals to `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`\n // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`\n bytes4 private constant ERC721_RECEIVED = 0xf0b9e5ba;\n\n // Mapping from token ID to owner\n mapping (uint256 => address) internal tokenOwner;\n\n // Mapping from token ID to approved address\n mapping (uint256 => address) internal tokenApprovals;\n\n // Mapping from owner to number of owned token\n mapping (address => uint256) internal ownedTokensCount;\n\n // Mapping from owner to operator approvals\n mapping (address => mapping (address => bool)) internal operatorApprovals;\n\n\n uint public testint;\n /**\n * @dev Guarantees msg.sender is owner of the given token\n * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender\n */\n modifier onlyOwnerOf(uint256 _tokenId) {\n require(ownerOf(_tokenId) == msg.sender);\n _;\n }\n\n /**\n * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator\n * @param _tokenId uint256 ID of the token to validate\n */\n modifier canTransfer(uint256 _tokenId) {\n require(isApprovedOrOwner(msg.sender, _tokenId));\n _;\n }\n\n constructor()\n public\n {\n // register the supported interfaces to conform to ERC721 via ERC165\n _registerInterface(InterfaceId_ERC721);\n _registerInterface(InterfaceId_ERC721Exists);\n }\n\n /**\n * @dev Gets the balance of the specified address\n * @param _owner address to query the balance of\n * @return uint256 representing the amount owned by the passed address\n */\n function balanceOf(address _owner) public view returns (uint256) {\n require(_owner != address(0));\n return ownedTokensCount[_owner];\n }\n\n /**\n * @dev Gets the owner of the specified token ID\n * @param _tokenId uint256 ID of the token to query the owner of\n * @return owner address currently marked as the owner of the given token ID\n */\n function ownerOf(uint256 _tokenId) public view returns (address) {\n address owner = tokenOwner[_tokenId];\n require(owner != address(0));\n return owner;\n }\n\n /**\n * @dev Returns whether the specified token exists\n * @param _tokenId uint256 ID of the token to query the existence of\n * @return whether the token exists\n */\n function exists(uint256 _tokenId) public view returns (bool) {\n address owner = tokenOwner[_tokenId];\n return owner != address(0);\n }\n\n /**\n * @dev Approves another address to transfer the given token ID\n * The zero address indicates there is no approved address.\n * There can only be one approved address per token at a given time.\n * Can only be called by the token owner or an approved operator.\n * @param _to address to be approved for the given token ID\n * @param _tokenId uint256 ID of the token to be approved\n */\n function approve(address _to, uint256 _tokenId) public {\n address owner = ownerOf(_tokenId);\n require(_to != owner);\n require(msg.sender == owner || isApprovedForAll(owner, msg.sender));\n\n tokenApprovals[_tokenId] = _to;\n emit Approval(owner, _to, _tokenId);\n }\n\n /**\n * @dev Gets the approved address for a token ID, or zero if no address set\n * @param _tokenId uint256 ID of the token to query the approval of\n * @return address currently approved for the given token ID\n */\n function getApproved(uint256 _tokenId) public view returns (address) {\n return tokenApprovals[_tokenId];\n }\n\n /**\n * @dev Sets or unsets the approval of a given operator\n * An operator is allowed to transfer all tokens of the sender on their behalf\n * @param _to operator address to set the approval\n * @param _approved representing the status of the approval to be set\n */\n function setApprovalForAll(address _to, bool _approved) public {\n require(_to != msg.sender);\n operatorApprovals[msg.sender][_to] = _approved;\n emit ApprovalForAll(msg.sender, _to, _approved);\n }\n\n /**\n * @dev Tells whether an operator is approved by a given owner\n * @param _owner owner address which you want to query the approval of\n * @param _operator operator address which you want to query the approval of\n * @return bool whether the given operator is approved by the given owner\n */\n function isApprovedForAll(\n address _owner,\n address _operator\n )\n public\n view\n returns (bool)\n {\n return operatorApprovals[_owner][_operator];\n }\n\n /**\n * @dev Transfers the ownership of a given token ID to another address\n * Usage of this method is discouraged, use `safeTransferFrom` whenever possible\n * Requires the msg sender to be the owner, approved, or operator\n * @param _from current owner of the token\n * @param _to address to receive the ownership of the given token ID\n * @param _tokenId uint256 ID of the token to be transferred\n */\n function transferFrom(\n address _from,\n address _to,\n uint256 _tokenId\n )\n public\n canTransfer(_tokenId)\n {\n require(_from != address(0));\n require(_to != address(0));\n\n clearApproval(_from, _tokenId);\n removeTokenFrom(_from, _tokenId);\n addTokenTo(_to, _tokenId);\n\n emit Transfer(_from, _to, _tokenId);\n }\n\n /**\n * @dev Safely transfers the ownership of a given token ID to another address\n * If the target address is a contract, it must implement `onERC721Received`,\n * which is called upon a safe transfer, and return the magic value\n * `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`; otherwise,\n * the transfer is reverted.\n *\n * Requires the msg sender to be the owner, approved, or operator\n * @param _from current owner of the token\n * @param _to address to receive the ownership of the given token ID\n * @param _tokenId uint256 ID of the token to be transferred\n */\n function safeTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId\n )\n public\n canTransfer(_tokenId)\n {\n // solium-disable-next-line arg-overflow\n safeTransferFrom(_from, _to, _tokenId, \"\");\n }\n\n /**\n * @dev Safely transfers the ownership of a given token ID to another address\n * If the target address is a contract, it must implement `onERC721Received`,\n * which is called upon a safe transfer, and return the magic value\n * `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`; otherwise,\n * the transfer is reverted.\n * Requires the msg sender to be the owner, approved, or operator\n * @param _from current owner of the token\n * @param _to address to receive the ownership of the given token ID\n * @param _tokenId uint256 ID of the token to be transferred\n * @param _data bytes data to send along with a safe transfer check\n */\n function safeTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId,\n bytes memory _data\n )\n public\n canTransfer(_tokenId)\n {\n transferFrom(_from, _to, _tokenId);\n // solium-disable-next-line arg-overflow\n require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));\n }\n\n /**\n * @dev Returns whether the given spender can transfer a given token ID\n * @param _spender address of the spender to query\n * @param _tokenId uint256 ID of the token to be transferred\n * @return bool whether the msg.sender is approved for the given token ID,\n * is an operator of the owner, or is the owner of the token\n */\n function isApprovedOrOwner(\n address _spender,\n uint256 _tokenId\n )\n internal\n view\n returns (bool)\n {\n address owner = ownerOf(_tokenId);\n // Disable solium check because of\n // https://github.com/duaraghav8/Solium/issues/175\n // solium-disable-next-line operator-whitespace\n return (\n _spender == owner ||\n getApproved(_tokenId) == _spender ||\n isApprovedForAll(owner, _spender)\n );\n }\n\n /**\n * @dev Internal function to mint a new token\n * Reverts if the given token ID already exists\n * @param _to The address that will own the minted token\n * @param _tokenId uint256 ID of the token to be minted by the msg.sender\n */\n function _mint(address _to, uint256 _tokenId) internal {\n require(_to != address(0));\n addTokenTo(_to, _tokenId);\n emit Transfer(address(0), _to, _tokenId);\n }\n\n /**\n * @dev Internal function to burn a specific token\n * Reverts if the token does not exist\n * @param _tokenId uint256 ID of the token being burned by the msg.sender\n */\n function _burn(address _owner, uint256 _tokenId) internal {\n clearApproval(_owner, _tokenId);\n removeTokenFrom(_owner, _tokenId);\n emit Transfer(_owner, address(0), _tokenId);\n }\n\n /**\n * @dev Internal function to clear current approval of a given token ID\n * Reverts if the given address is not indeed the owner of the token\n * @param _owner owner of the token\n * @param _tokenId uint256 ID of the token to be transferred\n */\n function clearApproval(address _owner, uint256 _tokenId) internal {\n require(ownerOf(_tokenId) == _owner);\n if (tokenApprovals[_tokenId] != address(0)) {\n tokenApprovals[_tokenId] = address(0);\n }\n }\n\n /**\n * @dev Internal function to add a token ID to the list of a given address\n * @param _to address representing the new owner of the given token ID\n * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address\n */\n function addTokenTo(address _to, uint256 _tokenId) internal {\n require(tokenOwner[_tokenId] == address(0));\n tokenOwner[_tokenId] = _to;\n ownedTokensCount[_to] = ownedTokensCount[_to].add(1);\n }\n\n /**\n * @dev Internal function to remove a token ID from the list of a given address\n * @param _from address representing the previous owner of the given token ID\n * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address\n */\n function removeTokenFrom(address _from, uint256 _tokenId) internal {\n require(ownerOf(_tokenId) == _from);\n ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);\n tokenOwner[_tokenId] = address(0);\n }\n\n /**\n * @dev Internal function to invoke `onERC721Received` on a target address\n * The call is not executed if the target address is not a contract\n * @param _from address representing the previous owner of the given token ID\n * @param _to target address that will receive the tokens\n * @param _tokenId uint256 ID of the token to be transferred\n * @param _data bytes optional data to send along with the call\n * @return whether the call correctly returned the expected magic value\n */\n function checkAndCallSafeTransfer(\n address _from,\n address _to,\n uint256 _tokenId,\n bytes memory _data\n )\n internal\n returns (bool)\n {\n if (!_to.isContract()) {\n return true;\n }\n bytes4 retval = ERC721Receiver(_to).onERC721Received(\n _from, _tokenId, _data);\n return (retval == ERC721_RECEIVED);\n }\n}\n\ncontract ERC721BasicTokenMock is ERC721BasicToken {\n function mint(address _to, uint256 _tokenId) public {\n super._mint(_to, _tokenId);\n }\n\n function burn(uint256 _tokenId) public {\n super._burn(ownerOf(_tokenId), _tokenId);\n }\n}\n"
},
"@openzeppelin/contracts/math/SafeMath.sol": {
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, \"SafeMath: division by zero\");\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b != 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC20/SafeERC20.sol": {
"content": "pragma solidity ^0.5.0;\n\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value);\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves.\n\n // A Solidity high level call has three parts:\n // 1. The target address is checked to verify it contains contract code\n // 2. The call itself is made, and success asserted\n // 3. The return value is decoded, which in turn checks the size of the returned data.\n // solhint-disable-next-line max-line-length\n require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = address(token).call(data);\n require(success, \"SafeERC20: low-level call failed\");\n\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Collection of functions related to the address type,\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * This test is non-exhaustive, and there may be false-negatives: during the\n * execution of a contract's constructor, its address will be reported as\n * not containing a contract.\n *\n * > It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies in extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n}\n"
},
"contracts/5/Fantastic12Factory.sol": {
"content": "pragma solidity 0.5.13;\n\nimport \"./Fantastic12.sol\";\n\ncontract Fantastic12Factory {\n address public constant DAI_ADDR = 0x6B175474E89094C44Da98b954EedeAC495271d0F;\n\n event CreateSquad(address indexed summoner, address squad);\n\n function createSquad(address _summoner, uint256 _withdrawLimit, uint256 _consensusThreshold)\n public\n returns (Fantastic12 _squad)\n {\n _squad = new Fantastic12();\n _squad.init(\n _summoner,\n DAI_ADDR,\n _withdrawLimit,\n _consensusThreshold\n );\n emit CreateSquad(_summoner, address(_squad));\n }\n}"
},
"contracts/5/mocks/MockERC20.sol": {
"content": "pragma solidity 0.5.13;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol\";\n\ncontract MockERC20 is ERC20Mintable {}"
},
"@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol": {
"content": "pragma solidity ^0.5.0;\n\nimport \"./ERC20.sol\";\nimport \"../../access/roles/MinterRole.sol\";\n\n/**\n * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`,\n * which have permission to mint (create) new tokens as they see fit.\n *\n * At construction, the deployer of the contract is the only minter.\n */\ncontract ERC20Mintable is ERC20, MinterRole {\n /**\n * @dev See `ERC20._mint`.\n *\n * Requirements:\n *\n * - the caller must have the `MinterRole`.\n */\n function mint(address account, uint256 amount) public onlyMinter returns (bool) {\n _mint(account, amount);\n return true;\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "pragma solidity ^0.5.0;\n\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\n\n/**\n * @dev Implementation of the `IERC20` interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using `_mint`.\n * For a generic mechanism see `ERC20Mintable`.\n *\n * *For a detailed writeup see our guide [How to implement supply\n * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an `Approval` event is emitted on calls to `transferFrom`.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard `decreaseAllowance` and `increaseAllowance`\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See `IERC20.approve`.\n */\ncontract ERC20 is IERC20 {\n using SafeMath for uint256;\n\n mapping (address => uint256) private _balances;\n\n mapping (address => mapping (address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n /**\n * @dev See `IERC20.totalSupply`.\n */\n function totalSupply() public view returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See `IERC20.balanceOf`.\n */\n function balanceOf(address account) public view returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See `IERC20.transfer`.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public returns (bool) {\n _transfer(msg.sender, recipient, amount);\n return true;\n }\n\n /**\n * @dev See `IERC20.allowance`.\n */\n function allowance(address owner, address spender) public view returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See `IERC20.approve`.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 value) public returns (bool) {\n _approve(msg.sender, spender, value);\n return true;\n }\n\n /**\n * @dev See `IERC20.transferFrom`.\n *\n * Emits an `Approval` event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of `ERC20`;\n *\n * Requirements:\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `value`.\n * - the caller must have allowance for `sender`'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to `approve` that can be used as a mitigation for\n * problems described in `IERC20.approve`.\n *\n * Emits an `Approval` event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {\n _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to `approve` that can be used as a mitigation for\n * problems described in `IERC20.approve`.\n *\n * Emits an `Approval` event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {\n _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to `transfer`, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a `Transfer` event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _balances[sender] = _balances[sender].sub(amount);\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a `Transfer` event with `from` set to the zero address.\n *\n * Requirements\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destoys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a `Transfer` event with `to` set to the zero address.\n *\n * Requirements\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 value) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _totalSupply = _totalSupply.sub(value);\n _balances[account] = _balances[account].sub(value);\n emit Transfer(account, address(0), value);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n *\n * This is internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an `Approval` event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 value) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = value;\n emit Approval(owner, spender, value);\n }\n\n /**\n * @dev Destoys `amount` tokens from `account`.`amount` is then deducted\n * from the caller's allowance.\n *\n * See `_burn` and `_approve`.\n */\n function _burnFrom(address account, uint256 amount) internal {\n _burn(account, amount);\n _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));\n }\n}\n"
},
"@openzeppelin/contracts/access/roles/MinterRole.sol": {
"content": "pragma solidity ^0.5.0;\n\nimport \"../Roles.sol\";\n\ncontract MinterRole {\n using Roles for Roles.Role;\n\n event MinterAdded(address indexed account);\n event MinterRemoved(address indexed account);\n\n Roles.Role private _minters;\n\n constructor () internal {\n _addMinter(msg.sender);\n }\n\n modifier onlyMinter() {\n require(isMinter(msg.sender), \"MinterRole: caller does not have the Minter role\");\n _;\n }\n\n function isMinter(address account) public view returns (bool) {\n return _minters.has(account);\n }\n\n function addMinter(address account) public onlyMinter {\n _addMinter(account);\n }\n\n function renounceMinter() public {\n _removeMinter(msg.sender);\n }\n\n function _addMinter(address account) internal {\n _minters.add(account);\n emit MinterAdded(account);\n }\n\n function _removeMinter(address account) internal {\n _minters.remove(account);\n emit MinterRemoved(account);\n }\n}\n"
},
"@openzeppelin/contracts/access/Roles.sol": {
"content": "pragma solidity ^0.5.0;\n\n/**\n * @title Roles\n * @dev Library for managing addresses assigned to a Role.\n */\nlibrary Roles {\n struct Role {\n mapping (address => bool) bearer;\n }\n\n /**\n * @dev Give an account access to this role.\n */\n function add(Role storage role, address account) internal {\n require(!has(role, account), \"Roles: account already has role\");\n role.bearer[account] = true;\n }\n\n /**\n * @dev Remove an account's access to this role.\n */\n function remove(Role storage role, address account) internal {\n require(has(role, account), \"Roles: account does not have role\");\n role.bearer[account] = false;\n }\n\n /**\n * @dev Check if an account has this role.\n * @return bool\n */\n function has(Role storage role, address account) internal view returns (bool) {\n require(account != address(0), \"Roles: account is the zero address\");\n return role.bearer[account];\n }\n}\n"
},
"contracts/5/PaidFantastic12Factory.sol": {
"content": "pragma solidity 0.5.13;\n\nimport \"./Fantastic12.sol\";\nimport \"@openzeppelin/contracts/ownership/Ownable.sol\";\nimport \"./EIP1167/CloneFactory.sol\";\n\ncontract PaidFantastic12Factory is Ownable, CloneFactory {\n address public constant DAI_ADDR = 0x6B175474E89094C44Da98b954EedeAC495271d0F;\n\n uint256 public priceInDAI = 0;\n address public beneficiary = 0x332D87209f7c8296389C307eAe170c2440830A47;\n address public template;\n\n event CreateSquad(address indexed summoner, address squad);\n\n constructor(address _template) public {\n template = _template;\n }\n\n function createSquad(address _summoner, uint256 _withdrawLimit, uint256 _consensusThreshold)\n public\n returns (Fantastic12 _squad)\n {\n // Transfer fee from msg.sender\n if (priceInDAI > 0) {\n IERC20 dai = IERC20(DAI_ADDR);\n require(dai.transferFrom(msg.sender, address(this), priceInDAI), \"DAI transferFrom failed\");\n require(dai.transfer(beneficiary, priceInDAI), \"DAI transfer failed\");\n }\n\n // Create squad\n _squad = Fantastic12(_toPayableAddr(createClone(template)));\n _squad.init(_summoner, DAI_ADDR, _withdrawLimit, _consensusThreshold);\n emit CreateSquad(_summoner, address(_squad));\n }\n\n function setPrice(uint256 _newPrice) public onlyOwner {\n priceInDAI = _newPrice;\n }\n\n function setBeneficiary(address _newBeneficiary) public onlyOwner {\n require(_newBeneficiary != address(0), \"0 address\");\n beneficiary = _newBeneficiary;\n }\n\n function _toPayableAddr(address _addr) internal pure returns (address payable) {\n return address(uint160(_addr));\n }\n}"
},
"@openzeppelin/contracts/ownership/Ownable.sol": {
"content": "pragma solidity ^0.5.0;\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be aplied to your functions to restrict their use to\n * the owner.\n */\ncontract Ownable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n _owner = msg.sender;\n emit OwnershipTransferred(address(0), _owner);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(isOwner(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Returns true if the caller is the current owner.\n */\n function isOwner() public view returns (bool) {\n return msg.sender == _owner;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * > Note: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public onlyOwner {\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n */\n function _transferOwnership(address newOwner) internal {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n"
},
"contracts/5/standard_bounties/v2/BountiesMetaTxRelayer.sol": {
"content": "pragma solidity 0.5.13;\npragma experimental ABIEncoderV2;\n\nimport \"./StandardBounties.sol\";\n\ncontract BountiesMetaTxRelayer {\n\n // This contract serves as a relayer for meta txns being sent to the Bounties contract\n\n StandardBounties public bountiesContract;\n mapping(address => uint) public replayNonce;\n\n\n constructor(address _contract) public {\n bountiesContract = StandardBounties(_contract);\n }\n\n function metaIssueBounty(\n bytes memory signature,\n address payable [] memory _issuers,\n address [] memory _approvers,\n string memory _data,\n uint _deadline,\n address _token,\n uint _tokenVersion,\n uint _nonce)\n public\n returns (uint)\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaIssueBounty\",\n _issuers,\n _approvers,\n _data,\n _deadline,\n _token,\n _tokenVersion,\n _nonce));\n address signer = getSigner(metaHash, signature);\n\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n return bountiesContract.issueBounty(address(uint160(signer)),\n _issuers,\n _approvers,\n _data,\n _deadline,\n _token,\n _tokenVersion);\n }\n\n function metaIssueAndContribute(\n bytes memory signature,\n address payable [] memory _issuers,\n address [] memory _approvers,\n string memory _data,\n uint _deadline,\n address _token,\n uint _tokenVersion,\n uint _depositAmount,\n uint _nonce)\n public\n payable\n returns (uint)\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaIssueAndContribute\",\n _issuers,\n _approvers,\n _data,\n _deadline,\n _token,\n _tokenVersion,\n _depositAmount,\n _nonce));\n address signer = getSigner(metaHash, signature);\n\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n if (msg.value > 0){\n return bountiesContract.issueAndContribute.value(msg.value)(address(uint160(signer)),\n _issuers,\n _approvers,\n _data,\n _deadline,\n _token,\n _tokenVersion,\n _depositAmount);\n } else {\n return bountiesContract.issueAndContribute(address(uint160(signer)),\n _issuers,\n _approvers,\n _data,\n _deadline,\n _token,\n _tokenVersion,\n _depositAmount);\n }\n\n }\n\n function metaContribute(\n bytes memory _signature,\n uint _bountyId,\n uint _amount,\n uint _nonce)\n public\n payable\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaContribute\",\n _bountyId,\n _amount,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n if (msg.value > 0){\n bountiesContract.contribute.value(msg.value)(address(uint160(signer)), _bountyId, _amount);\n } else {\n bountiesContract.contribute(address(uint160(signer)), _bountyId, _amount);\n }\n }\n\n\n function metaRefundContribution(\n bytes memory _signature,\n uint _bountyId,\n uint _contributionId,\n uint _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaRefundContribution\",\n _bountyId,\n _contributionId,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.refundContribution(signer, _bountyId, _contributionId);\n }\n\n function metaRefundMyContributions(\n bytes memory _signature,\n uint _bountyId,\n uint [] memory _contributionIds,\n uint _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaRefundMyContributions\",\n _bountyId,\n _contributionIds,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.refundMyContributions(signer, _bountyId, _contributionIds);\n }\n\n function metaRefundContributions(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n uint [] memory _contributionIds,\n uint _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaRefundContributions\",\n _bountyId,\n _issuerId,\n _contributionIds,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.refundContributions(signer, _bountyId, _issuerId, _contributionIds);\n }\n\n function metaDrainBounty(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n uint [] memory _amounts,\n uint _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaDrainBounty\",\n _bountyId,\n _issuerId,\n _amounts,\n _nonce));\n address payable signer = address(uint160(getSigner(metaHash, _signature)));\n\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.drainBounty(signer, _bountyId, _issuerId, _amounts);\n }\n\n function metaPerformAction(\n bytes memory _signature,\n uint _bountyId,\n string memory _data,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaPerformAction\",\n _bountyId,\n _data,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.performAction(signer, _bountyId, _data);\n }\n\n function metaFulfillBounty(\n bytes memory _signature,\n uint _bountyId,\n address payable [] memory _fulfillers,\n string memory _data,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaFulfillBounty\",\n _bountyId,\n _fulfillers,\n _data,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.fulfillBounty(signer, _bountyId, _fulfillers, _data);\n }\n\n function metaUpdateFulfillment(\n bytes memory _signature,\n uint _bountyId,\n uint _fulfillmentId,\n address payable [] memory _fulfillers,\n string memory _data,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaUpdateFulfillment\",\n _bountyId,\n _fulfillmentId,\n _fulfillers,\n _data,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.updateFulfillment(signer, _bountyId, _fulfillmentId, _fulfillers, _data);\n }\n\n function metaAcceptFulfillment(\n bytes memory _signature,\n uint _bountyId,\n uint _fulfillmentId,\n uint _approverId,\n uint [] memory _tokenAmounts,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaAcceptFulfillment\",\n _bountyId,\n _fulfillmentId,\n _approverId,\n _tokenAmounts,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.acceptFulfillment(signer,\n _bountyId,\n _fulfillmentId,\n _approverId,\n _tokenAmounts);\n }\n\n function metaFulfillAndAccept(\n bytes memory _signature,\n uint _bountyId,\n address payable [] memory _fulfillers,\n string memory _data,\n uint _approverId,\n uint [] memory _tokenAmounts,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaFulfillAndAccept\",\n _bountyId,\n _fulfillers,\n _data,\n _approverId,\n _tokenAmounts,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.fulfillAndAccept(signer,\n _bountyId,\n _fulfillers,\n _data,\n _approverId,\n _tokenAmounts);\n }\n\n function metaChangeBounty(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n address payable [] memory _issuers,\n address payable [] memory _approvers,\n string memory _data,\n uint _deadline,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaChangeBounty\",\n _bountyId,\n _issuerId,\n _issuers,\n _approvers,\n _data,\n _deadline,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.changeBounty(signer,\n _bountyId,\n _issuerId,\n _issuers,\n _approvers,\n _data,\n _deadline);\n }\n\n function metaChangeIssuer(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n uint _issuerIdToChange,\n address payable _newIssuer,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaChangeIssuer\",\n _bountyId,\n _issuerId,\n _issuerIdToChange,\n _newIssuer,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.changeIssuer(signer,\n _bountyId,\n _issuerId,\n _issuerIdToChange,\n _newIssuer);\n }\n\n function metaChangeApprover(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n uint _approverId,\n address payable _approver,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaChangeApprover\",\n _bountyId,\n _issuerId,\n _approverId,\n _approver,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.changeApprover(signer,\n _bountyId,\n _issuerId,\n _approverId,\n _approver);\n }\n\n function metaChangeData(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n string memory _data,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaChangeData\",\n _bountyId,\n _issuerId,\n _data,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.changeData(signer,\n _bountyId,\n _issuerId,\n _data);\n }\n\n function metaChangeDeadline(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n uint _deadline,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaChangeDeadline\",\n _bountyId,\n _issuerId,\n _deadline,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.changeDeadline(signer,\n _bountyId,\n _issuerId,\n _deadline);\n }\n\n function metaAddIssuers(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n address payable [] memory _issuers,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaAddIssuers\",\n _bountyId,\n _issuerId,\n _issuers,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.addIssuers(signer,\n _bountyId,\n _issuerId,\n _issuers);\n }\n\n function metaReplaceIssuers(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n address payable [] memory _issuers,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaReplaceIssuers\",\n _bountyId,\n _issuerId,\n _issuers,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.replaceIssuers(signer,\n _bountyId,\n _issuerId,\n _issuers);\n }\n\n function metaAddApprovers(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n address payable [] memory _approvers,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaAddApprovers\",\n _bountyId,\n _issuerId,\n _approvers,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.addIssuers(signer,\n _bountyId,\n _issuerId,\n _approvers);\n }\n\n function metaReplaceApprovers(\n bytes memory _signature,\n uint _bountyId,\n uint _issuerId,\n address payable [] memory _approvers,\n uint256 _nonce)\n public\n {\n bytes32 metaHash = keccak256(abi.encode(address(this),\n \"metaReplaceApprovers\",\n _bountyId,\n _issuerId,\n _approvers,\n _nonce));\n address signer = getSigner(metaHash, _signature);\n //make sure signer doesn't come back as 0x0\n require(signer != address(0));\n require(_nonce == replayNonce[signer]);\n\n //increase the nonce to prevent replay attacks\n replayNonce[signer]++;\n\n bountiesContract.replaceIssuers(signer,\n _bountyId,\n _issuerId,\n _approvers);\n }\n\n function getSigner(\n bytes32 _hash,\n bytes memory _signature)\n internal\n pure\n returns (address)\n {\n bytes32 r;\n bytes32 s;\n uint8 v;\n if (_signature.length != 65) {\n return address(0);\n }\n assembly {\n r := mload(add(_signature, 32))\n s := mload(add(_signature, 64))\n v := byte(0, mload(add(_signature, 96)))\n }\n if (v < 27) {\n v += 27;\n }\n if (v != 27 && v != 28) {\n return address(0);\n } else {\n return ecrecover(keccak256(\n abi.encode(\"\\x19Ethereum Signed Message:\\n32\", _hash)\n ), v, r, s);\n }\n }\n}\n"
}
},
"settings": {
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
}
}
}} | XXX Currently there is no better way to check if there is a contract in an address\n than to check the size of the code at that address.\n See https:ethereum.stackexchange.com/a/14016/36603\n for more details about how this works.\n TODO Check this again before the Serenity release, because all addresses will be\n contracts then.\n solium-disable-next-line security/no-inline-assembly\n assembly { size := extcodesize(addr) }\n return size > 0;\n }\n\n}\n\n/**\n * @title ERC165\n * @dev https:github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md\n */\ninterface ERC165 {\n\n /**\n * @notice Query if a contract implements an interface\n * @param _interfaceId The interface identifier, as specified in ERC-165\n * @dev Interface identification is specified in ERC-165. This function\n * uses less than 30,000 gas.\n */\n function supportsInterface(bytes4 _interfaceId)\n external\n view\n returns (bool);\n}\n\n\n/**\n * @title SupportsInterfaceWithLookup\n * @author Matt Condon (@shrugs)\n * @dev Implements ERC165 using a lookup table.\n */\ncontract SupportsInterfaceWithLookup is ERC165 {\n bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;\n /**\n * 0x01ffc9a7 ===\n * bytes4(keccak256('supportsInterface(bytes4)'))\n */\n\n /**\n * @dev a mapping of interface id to whether or not it's supported\n */\n mapping(bytes4 => bool) internal supportedInterfaces;\n\n /**\n * @dev A contract implementing SupportsInterfaceWithLookup\n * implement ERC165 itself\n */\n constructor()\n public\n {\n _registerInterface(InterfaceId_ERC165);\n }\n\n /**\n * @dev implement supportsInterface(bytes4) using a lookup table\n */\n function supportsInterface(bytes4 _interfaceId)\n external\n view\n returns (bool)\n {\n return supportedInterfaces[_interfaceId];\n }\n\n /**\n * @dev private method for registering an interface\n */\n function _registerInterface(bytes4 _interfaceId)\n internal\n {\n require(_interfaceId != 0xffffffff);\n supportedInterfaces[_interfaceId] = true;\n }\n}\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ncontract ERC721Receiver {\n /**\n * @dev Magic value to be returned upon successful reception of an NFT\n * Equals to `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`,\n * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`\n */\n bytes4 internal constant ERC721_RECEIVED = 0xf0b9e5ba;\n\n /**\n * @notice Handle the receipt of an NFT\n * @dev The ERC721 smart contract calls this function on the recipient\n * after a `safetransfer`. This function MAY throw to revert and reject the\n * transfer. This function MUST use 50,000 gas or less. Return of other\n * than the magic value MUST result in the transaction being reverted.\n * Note: the contract address is always the message sender.\n * @param _from The sending address\n * @param _tokenId The NFT identifier which is being transfered\n * @param _data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`\n */\n function onERC721Received(\n address _from,\n uint256 _tokenId,\n bytes memory _data\n )\n public\n returns(bytes4);\n}\n\n/**\n * @title ERC721 Non-Fungible Token Standard basic interface\n * @dev see https:github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md\n */\ncontract ERC721Basic is ERC165 {\n event Transfer(\n address _from,\n address _to,\n uint256 _tokenId\n );\n event Approval(\n address _owner,\n address _approved,\n uint256 _tokenId\n );\n event ApprovalForAll(\n address _owner,\n address _operator,\n bool _approved\n );\n\n function balanceOf(address _owner) public view returns (uint256 _balance);\n function ownerOf(uint256 _tokenId) public view returns (address _owner);\n function exists(uint256 _tokenId) public view returns (bool _exists);\n\n function approve(address _to, uint256 _tokenId) public;\n function getApproved(uint256 _tokenId)\n public view returns (address _operator);\n\n function setApprovalForAll(address _operator, bool _approved) public;\n function isApprovedForAll(address _owner, address _operator)\n public view returns (bool);\n\n function transferFrom(address _from, address _to, uint256 _tokenId) public;\n function safeTransferFrom(address _from, address _to, uint256 _tokenId)\n public;\n\n function safeTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId,\n bytes memory _data\n )\n public;\n}\n\n/**\n * @title ERC721 Non-Fungible Token Standard basic implementation\n * @dev see https:github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md\n */\ncontract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {\n\n bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;\n /*\n * 0x80ac58cd ===\n * bytes4(keccak256('balanceOf(address)')) ^\n * bytes4(keccak256('ownerOf(uint256)')) ^\n * bytes4(keccak256('approve(address,uint256)')) ^\n * bytes4(keccak256('getApproved(uint256)')) ^\n * bytes4(keccak256('setApprovalForAll(address,bool)')) ^\n * bytes4(keccak256('isApprovedForAll(address,address)')) ^\n * bytes4(keccak256('transferFrom(address,address,uint256)')) ^\n * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^\n * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))\n */\n\n bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;\n /*\n * 0x4f558e79 ===\n * bytes4(keccak256('exists(uint256)'))\n */\n\n using SafeMath for uint256;\n using AddressUtils for address;\n\n Equals to `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`\n which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`\n bytes4 private constant ERC721_RECEIVED = 0xf0b9e5ba;\n\n Mapping from token ID to owner\n mapping (uint256 => address) internal tokenOwner;\n\n Mapping from token ID to approved address\n mapping (uint256 => address) internal tokenApprovals;\n\n Mapping from owner to number of owned token\n mapping (address => uint256) internal ownedTokensCount;\n\n Mapping from owner to operator approvals\n mapping (address => mapping (address => bool)) internal operatorApprovals;\n\n\n uint public testint;\n /**\n * @dev Guarantees msg.sender is owner of the given token\n * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender\n */\n modifier onlyOwnerOf(uint256 _tokenId) {\n require(ownerOf(_tokenId) == msg.sender);\n _;\n }\n\n /**\n * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator\n * @param _tokenId uint256 ID of the token to validate\n */\n modifier canTransfer(uint256 _tokenId) {\n require(isApprovedOrOwner(msg.sender, _tokenId));\n _;\n }\n\n constructor()\n public\n {\n register the supported interfaces to conform to ERC721 via ERC165\n _registerInterface(InterfaceId_ERC721);\n _registerInterface(InterfaceId_ERC721Exists);\n }\n\n /**\n * @dev Gets the balance of the specified address\n * @param _owner address to query the balance of\n * @return uint256 representing the amount owned by the passed address\n */\n function balanceOf(address _owner) public view returns (uint256) {\n require(_owner != address(0));\n return ownedTokensCount[_owner];\n }\n\n /**\n * @dev Gets the owner of the specified token ID\n * @param _tokenId uint256 ID of the token to query the owner of\n * @return owner address currently marked as the owner of the given token ID\n */\n function ownerOf(uint256 _tokenId) public view returns (address) {\n address owner = tokenOwner[_tokenId];\n require(owner != address(0));\n return owner;\n }\n\n /**\n * @dev Returns whether the specified token exists\n * @param _tokenId uint256 ID of the token to query the existence of\n * @return whether the token exists\n */\n function exists(uint256 _tokenId) public view returns (bool) {\n address owner = tokenOwner[_tokenId];\n return owner != address(0);\n }\n\n /**\n * @dev Approves another address to transfer the given token ID\n * The zero address indicates there is no approved address.\n * There can only be one approved address per token at a given time.\n * Can only be called by the token owner or an approved operator.\n * @param _to address to be approved for the given token ID\n * @param _tokenId uint256 ID of the token to be approved\n */\n function approve(address _to, uint256 _tokenId) public {\n address owner = ownerOf(_tokenId);\n require(_to != owner);\n require(msg.sender == owner || isApprovedForAll(owner, msg.sender));\n\n tokenApprovals[_tokenId] = _to;\n emit Approval(owner, _to, _tokenId);\n }\n\n /**\n * @dev Gets the approved address for a token ID, or zero if no address set\n * @param _tokenId uint256 ID of the token to query the approval of\n * @return address currently approved for the given token ID\n */\n function getApproved(uint256 _tokenId) public view returns (address) {\n return tokenApprovals[_tokenId];\n }\n\n /**\n * @dev Sets or unsets the approval of a given operator\n * An operator is allowed to transfer all tokens of the sender on their behalf\n * @param _to operator address to set the approval\n * @param _approved representing the status of the approval to be set\n */\n function setApprovalForAll(address _to, bool _approved) public {\n require(_to != msg.sender);\n operatorApprovals[msg.sender][_to] = _approved;\n emit ApprovalForAll(msg.sender, _to, _approved);\n }\n\n /**\n * @dev Tells whether an operator is approved by a given owner\n * @param _owner owner address which you want to query the approval of\n * @param _operator operator address which you want to query the approval of\n * @return bool whether the given operator is approved by the given owner\n */\n function isApprovedForAll(\n address _owner,\n address _operator\n )\n public\n view\n returns (bool)\n {\n return operatorApprovals[_owner][_operator];\n }\n\n /**\n * @dev Transfers the ownership of a given token ID to another address\n * Usage of this method is discouraged, use `safeTransferFrom` whenever possible\n * Requires the msg sender to be the owner, approved, or operator\n * @param _from current owner of the token\n * @param _to address to receive the ownership of the given token ID\n * @param _tokenId uint256 ID of the token to be transferred\n */\n function transferFrom(\n address _from,\n address _to,\n uint256 _tokenId\n )\n public\n canTransfer(_tokenId)\n {\n require(_from != address(0));\n require(_to != address(0));\n\n clearApproval(_from, _tokenId);\n removeTokenFrom(_from, _tokenId);\n addTokenTo(_to, _tokenId);\n\n emit Transfer(_from, _to, _tokenId);\n }\n\n /**\n * @dev Safely transfers the ownership of a given token ID to another address\n * If the target address is a contract, it must implement `onERC721Received`,\n * which is called upon a safe transfer, and return the magic value\n * `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`; otherwise,\n * the transfer is reverted.\n *\n * Requires the msg sender to be the owner, approved, or operator\n * @param _from current owner of the token\n * @param _to address to receive the ownership of the given token ID\n * @param _tokenId uint256 ID of the token to be transferred\n */\n function safeTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId\n )\n public\n canTransfer(_tokenId)\n {\n solium-disable-next-line arg-overflow\n safeTransferFrom(_from, _to, _tokenId, \"\");\n }\n\n /**\n * @dev Safely transfers the ownership of a given token ID to another address\n * If the target address is a contract, it must implement `onERC721Received`,\n * which is called upon a safe transfer, and return the magic value\n * `bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))`; otherwise,\n * the transfer is reverted.\n * Requires the msg sender to be the owner, approved, or operator\n * @param _from current owner of the token\n * @param _to address to receive the ownership of the given token ID\n * @param _tokenId uint256 ID of the token to be transferred\n * @param _data bytes data to send along with a safe transfer check\n */\n function safeTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId,\n bytes memory _data\n )\n public\n canTransfer(_tokenId)\n {\n transferFrom(_from, _to, _tokenId);\n solium-disable-next-line arg-overflow\n require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));\n }\n\n /**\n * @dev Returns whether the given spender can transfer a given token ID\n * @param _spender address of the spender to query\n * @param _tokenId uint256 ID of the token to be transferred\n * @return bool whether the msg.sender is approved for the given token ID,\n * is an operator of the owner, or is the owner of the token\n */\n function isApprovedOrOwner(\n address _spender,\n uint256 _tokenId\n )\n internal\n view\n returns (bool)\n {\n address owner = ownerOf(_tokenId);\n Disable solium check because of\n https:github.com/duaraghav8/Solium/issues/175\n solium-disable-next-line operator-whitespace\n return (\n _spender == owner ||\n getApproved(_tokenId) == _spender ||\n isApprovedForAll(owner, _spender)\n );\n }\n\n /**\n * @dev Internal function to mint a new token\n * Reverts if the given token ID already exists\n * @param _to The address that will own the minted token\n * @param _tokenId uint256 ID of the token to be minted by the msg.sender\n */\n function _mint(address _to, uint256 _tokenId) internal {\n require(_to != address(0));\n addTokenTo(_to, _tokenId);\n emit Transfer(address(0), _to, _tokenId);\n }\n\n /**\n * @dev Internal function to burn a specific token\n * Reverts if the token does not exist\n * @param _tokenId uint256 ID of the token being burned by the msg.sender\n */\n function _burn(address _owner, uint256 _tokenId) internal {\n clearApproval(_owner, _tokenId);\n removeTokenFrom(_owner, _tokenId);\n emit Transfer(_owner, address(0), _tokenId);\n }\n\n /**\n * @dev Internal function to clear current approval of a given token ID\n * Reverts if the given address is not indeed the owner of the token\n * @param _owner owner of the token\n * @param _tokenId uint256 ID of the token to be transferred\n */\n function clearApproval(address _owner, uint256 _tokenId) internal {\n require(ownerOf(_tokenId) == _owner);\n if (tokenApprovals[_tokenId] != address(0)) {\n tokenApprovals[_tokenId] = address(0);\n }\n }\n\n /**\n * @dev Internal function to add a token ID to the list of a given address\n * @param _to address representing the new owner of the given token ID\n * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address\n */\n function addTokenTo(address _to, uint256 _tokenId) internal {\n require(tokenOwner[_tokenId] == address(0));\n tokenOwner[_tokenId] = _to;\n ownedTokensCount[_to] = ownedTokensCount[_to].add(1);\n }\n\n /**\n * @dev Internal function to remove a token ID from the list of a given address\n * @param _from address representing the previous owner of the given token ID\n * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address\n */\n function removeTokenFrom(address _from, uint256 _tokenId) internal {\n require(ownerOf(_tokenId) == _from);\n ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);\n tokenOwner[_tokenId] = address(0);\n }\n\n /**\n * @dev Internal function to invoke `onERC721Received` on a target address\n * The call is not executed if the target address is not a contract\n * @param _from address representing the previous owner of the given token ID\n * @param _to target address that will receive the tokens\n * @param _tokenId uint256 ID of the token to be transferred\n * @param _data bytes optional data to send along with the call\n * @return whether the call correctly returned the expected magic value\n */\n function checkAndCallSafeTransfer(\n address _from,\n address _to,\n uint256 _tokenId,\n bytes memory _data\n )\n internal\n returns (bool)\n {\n if (!_to.isContract()) {\n return true;\n }\n bytes4 retval = ERC721Receiver(_to).onERC721Received(\n _from, _tokenId, _data);\n return (retval == ERC721_RECEIVED);\n }\n}\n\ncontract ERC721BasicTokenMock is ERC721BasicToken {\n function mint(address _to, uint256 _tokenId) public {\n super._mint(_to, _tokenId);\n }\n\n function burn(uint256 _tokenId) public {\n super._burn(ownerOf(_tokenId), _tokenId);\n }\n}\n"
| "content": " pragma solidity 0.5.13;\n\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n/**\n * Utility library of inline functions on addresses\n */\nlibrary AddressUtils {\n\n /**\n * Returns whether the target address is a contract\n * @dev This function will return false if invoked during the constructor of a contract,\n * as the code is not actually created until after the constructor finishes.\n * @param addr address to check\n * @return whether the target address is a contract\n */\n function isContract(address addr) internal view returns (bool) {\n uint256 size;\n | 7,322,437 | [
1,
15639,
15212,
1915,
353,
1158,
7844,
4031,
358,
866,
309,
1915,
353,
279,
6835,
316,
392,
1758,
64,
82,
377,
2353,
358,
866,
326,
963,
434,
326,
981,
622,
716,
1758,
8403,
82,
377,
2164,
2333,
30,
546,
822,
379,
18,
3772,
16641,
18,
832,
19,
69,
19,
3461,
24171,
19,
5718,
26,
4630,
64,
82,
377,
364,
1898,
3189,
2973,
3661,
333,
6330,
8403,
82,
377,
2660,
2073,
333,
3382,
1865,
326,
1275,
275,
560,
3992,
16,
2724,
777,
6138,
903,
506,
64,
82,
377,
20092,
1508,
8403,
82,
377,
3704,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
17,
10047,
17,
28050,
64,
82,
565,
19931,
288,
963,
519,
1110,
7000,
554,
12,
4793,
13,
289,
64,
82,
565,
327,
963,
405,
374,
9747,
82,
225,
289,
64,
82,
64,
82,
6280,
82,
64,
82,
24441,
82,
282,
4232,
39,
28275,
64,
82,
282,
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,
1377,
315,
1745,
6877,
315,
10878,
18035,
560,
374,
18,
25,
18,
3437,
9747,
82,
64,
82,
5666,
1239,
36,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
15949,
19,
9890,
10477,
18,
18281,
2412,
9747,
82,
64,
82,
26873,
64,
82,
380,
13134,
5313,
434,
6370,
4186,
603,
6138,
64,
82,
1195,
64,
82,
12083,
5267,
1989,
18890,
82,
64,
82,
225,
1783,
64,
82,
282,
380,
2860,
2856,
326,
1018,
1758,
353,
279,
6835,
64,
82,
282,
380,
632,
5206,
1220,
445,
903,
327,
629,
309,
8187,
4982,
326,
3885,
434,
279,
6835,
17211,
82,
282,
380,
487,
326,
981,
353,
486,
6013,
2522,
3180,
1839,
326,
3885,
27609,
8403,
82,
282,
380,
632,
891,
3091,
1758,
358,
866,
64,
82,
282,
380,
632,
2463,
2856,
326,
1018,
1758,
353,
279,
6835,
64,
82,
282,
1195,
64,
82,
225,
445,
353,
8924,
12,
2867,
3091,
13,
2713,
1476,
1135,
261,
6430,
13,
18890,
82,
565,
2254,
5034,
963,
9747,
82,
377,
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
] |
./full_match/1/0xa6Ae1C1Dc3024ec951972A10A7043bc7425F1f57/sources/contracts/ArtblocksOracle.sol | Otherwise, between 0 and 255 tokens in this word are finalized; form a mask of their indices. (This subtraction doesn't underflow because the shift produces a nonzero value, given the bounds on `_numFinalizedSinceStartOfWord`.) | return (1 << _numFinalizedSinceStartOfWord) - 1;
| 16,526,911 | [
1,
8290,
2460,
16,
3086,
374,
471,
4561,
2430,
316,
333,
2076,
854,
727,
1235,
31,
646,
279,
3066,
434,
3675,
4295,
18,
261,
2503,
720,
25693,
3302,
1404,
3613,
2426,
2724,
326,
4654,
15505,
279,
16966,
460,
16,
864,
326,
4972,
603,
1375,
67,
2107,
7951,
1235,
9673,
1685,
951,
3944,
8338,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3639,
327,
261,
21,
2296,
389,
2107,
7951,
1235,
9673,
1685,
951,
3944,
13,
300,
404,
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
] |
./partial_match/1/0xE4dD566b410Fe45db55BD9F5f928269290B0a674/sources/SecurityToken.sol | * @notice Burn function used to burn the securityToken on behalf of someone else @param _from Address for whom to burn tokens @param _value No. of tokens that get burned @param _data data to indicate validation/ | function burnFromWithData(address _from, uint256 _value, bytes _data) public onlyModule(BURN_KEY) {
require(_value <= allowed[_from][msg.sender], "Value too high");
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
require(_burn(_from, _value, _data), "Burn invalid");
}
| 4,335,626 | [
1,
38,
321,
445,
1399,
358,
18305,
326,
4373,
1345,
603,
12433,
6186,
434,
18626,
469,
225,
389,
2080,
5267,
364,
600,
362,
358,
18305,
2430,
225,
389,
1132,
2631,
18,
434,
2430,
716,
336,
18305,
329,
225,
389,
892,
501,
358,
10768,
3379,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
18305,
1265,
1190,
751,
12,
2867,
389,
2080,
16,
2254,
5034,
389,
1132,
16,
1731,
389,
892,
13,
1071,
1338,
3120,
12,
38,
8521,
67,
3297,
13,
288,
203,
3639,
2583,
24899,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
6487,
315,
620,
4885,
3551,
8863,
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,
2583,
24899,
70,
321,
24899,
2080,
16,
389,
1132,
16,
389,
892,
3631,
315,
38,
321,
2057,
8863,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title WrappedBustOfRomeOneYear
/// @author jpegmint.xyz
import "./INiftyBuilder.sol";
import "./@jpegmint/contracts/ERC721Wrapper.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
/**
* _ __ __ ___ __ ___ ___
* | | /| / /______ ____ ___ ___ ___/ / / _ )__ _____ / /_ ___ / _/ / _ \___ __ _ ___
* | |/ |/ / __/ _ `/ _ \/ _ \/ -_) _ / / _ / // (_-</ __/ / _ \/ _/ / , _/ _ \/ ' \/ -_)
* |__/|__/_/ \_,_/ .__/ .__/\__/\_,_/ /____/\_,_/___/\__/ \___/_/ /_/|_|\___/_/_/_/\__/
* /_/ /_/
*
* @dev Wrapping contract for ROME token to improve the TokenURI metadata.
*/
contract WrappedBustOfRomeOneYear is ERC721Wrapper, Ownable {
using Strings for uint256;
INiftyBuilder private immutable _niftyBuilderInstance;
constructor(address niftyBuilderAddress) ERC721("Wrapped Bust of Rome (One Year)", "wROME") {
_niftyBuilderInstance = INiftyBuilder(niftyBuilderAddress);
}
/**
* @dev Add access control and force ROME contract address.
*/
function updateApprovedTokenRanges(address contract_, uint256 minTokenId, uint256 maxTokenId) public override onlyOwner {
require(contract_ == address(_niftyBuilderInstance), 'wROME: Can only approve ROME contract tokens.');
_updateApprovedTokenRanges(contract_, minTokenId, maxTokenId);
}
/**
* @dev TokenURI override to return metadata and IPFS/Arweave assets on-chain and dynamically.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "wROME: URI query for nonexistent token");
string memory mintNumber = (tokenId - 100010000).toString();
string memory ipfsHash = _niftyBuilderInstance.tokenIPFSHash(tokenId);
string memory arweaveHash = _getTokenArweaveHash(ipfsHash);
bytes memory byteString;
byteString = abi.encodePacked(byteString, 'data:application/json;utf8,{');
byteString = abi.encodePacked(byteString, '"name": "Eroding and Reforming Bust of Rome (One Year) #', mintNumber, '/671",');
byteString = abi.encodePacked(byteString, '"created_by": "Daniel Arsham",');
byteString = abi.encodePacked(byteString
,'"description": "**Daniel Arsham** (b. 1980)\\n\\n'
,'***Eroding and Reforming Bust of Rome (One Year)***, 2021\\n\\n'
,'With his debut NFT release, Daniel Arsham introduces a concept never before seen on Nifty Gateway. '
,'His piece will erode, reform, and change based on the time of year.",'
);
byteString = abi.encodePacked(byteString, '"external_url": "https://niftygateway.com/collections/danielarsham",');
byteString = abi.encodePacked(byteString
,'"image": "https://arweave.net/', arweaveHash, '",'
,'"image_url": "https://arweave.net/', arweaveHash, '",'
,'"animation": "ipfs://', ipfsHash, '",'
,'"animation_url": "ipfs://', ipfsHash, '",'
);
byteString = abi.encodePacked(byteString, '"attributes":[{"trait_type": "Edition", "display_type": "number", "value": ', mintNumber, ', "max_value": 671}]');
byteString = abi.encodePacked(byteString, '}');
return string(byteString);
}
/**
* @dev Returns Arweave hash for the preview image matching given IPFS hash.
*/
function _getTokenArweaveHash(string memory ipfsHash) private pure returns (string memory) {
bytes32 ipfsMatcher = keccak256(abi.encodePacked(ipfsHash));
if (ipfsMatcher == keccak256("QmQdb77jfHZSwk8dGpN3mqx8q4N7EUNytiAgEkXrMPbMVw")) return "iOKh8ppTX5831s9ip169PfcqZ265rlz_kH-oyDXELtA"; //State 1
else if (ipfsMatcher == keccak256("QmS3kaQnxb28vcXQg35PrGarJKkSysttZdNLdZp3JquttQ")) return "4iJ3Igr90bfEkBMeQv1t2S4ctK2X-I18hnbal2YFfWI"; //State 2
else if (ipfsMatcher == keccak256("QmX8beRtZAsed6naFWqddKejV33NoXotqZoGTuDaV5SHqN")) return "y4yuf5VvfAYOl3Rm5DTsAaneJDXwFJGBThI6VG3b7co"; //State 3
else if (ipfsMatcher == keccak256("QmQvsAMYzJm8kGQ7YNF5ziWUb6hr7vqdmkrn1qEPDykYi4")) return "29SOcovLFC5Q4B-YJzgisGgRXllDHoN_l5c8Tan3jHs"; //State 4
else if (ipfsMatcher == keccak256("QmZwHt9ZhCgVMqpcFDhwKSA3higVYQXzyaPqh2BPjjXJXU")) return "d8mJGLKJhg1Gl2OW1qQjcH8Y8tYBCvNWUuGH6iXd18U"; //State 5
else if (ipfsMatcher == keccak256("Qmd2MNfgzPYXGMS1ZgdsiWuAkriRRx15pfRXU7ZVK22jce")) return "siy0OInjmvElSk2ORJ4VNiQC1_dkdKzNRpmkOBBy2hA"; //State 6
else if (ipfsMatcher == keccak256("QmWcYzNdUYbMzrM7bGgTZXVE4GBm7v4dQneKb9fxgjMdAX")) return "5euBxS7JvRrqb7fxh4wLjEW5abPswocAGTHjqlrkyBE"; //State 7
else if (ipfsMatcher == keccak256("QmaXX7VuBY1dCeK78TTGEvYLTF76sf6fnzK7TJSni4PHxj")) return "7IK1u-DsuAj0nQzpwmQpo66dwpWx8PS9i-xv6aS6y6I"; //State 8
else if (ipfsMatcher == keccak256("QmaqeJnzF2cAdfDrYRAw6VwzNn9dY9bKTyUuTHg1gUSQY7")) return "LWpLIs3-PUvV6WvXa-onc5QZ5FeYiEpiIwRfc_u64ss"; //State 9
else if (ipfsMatcher == keccak256("QmSZquD6yGy5QvsJnygXUnWKrsKJvk942L8nzs6YZFKbxY")) return "vzLvsueGrzpVI_MZBogAw57Pi1OdynahcolZPpvhEQI"; //State 10
else if (ipfsMatcher == keccak256("QmYtdrfPd3jAWWpjkd24NzLGqH5TDsHNvB8Qtqu6xnBcJF")) return "iEh79QQjaMjKd0I6d6eM8UYcFw-pj5_gBdGhTOTB54g"; //State 11
else if (ipfsMatcher == keccak256("QmesagGNeyjDvJ2N5oc8ykBiwsiE7gdk9vnfjjAe3ipjx4")) return "b132CTM45LOEMwzOqxnPqtDqlPPwcaQ0ztQ5OWhBnvQ"; //State 12
revert('wROME: Invalid IPFS hash');
}
/**
* Recovery function to extract orphaned ROME tokens. Works only if wROME contract
* owns unwrapped ROME token.
*/
function recoverOrphanedToken(uint256 tokenId) external onlyOwner {
require(!_exists(tokenId), "wROME: can't recover wrapped token");
require(_niftyBuilderInstance.ownerOf(tokenId) == address(this), "wROME: can't recover token that is not own");
_niftyBuilderInstance.safeTransferFrom(address(this), msg.sender, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract 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 { }
}
// SPDX-License-Identifier: MIT
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);
}
}
// 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 () {
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.8.0;
/// @author jpegmint.xyz
import "./IERC721Wrapper.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
/**
* @title ERC721 token wrapping base.
*/
abstract contract ERC721Wrapper is ERC721, IERC721Wrapper, ReentrancyGuard {
struct TokenIdRange {
uint256 minTokenId;
uint256 maxTokenId;
}
mapping(address => TokenIdRange) private _approvedTokenRanges;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Wrapper).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Transfers contract/tokenId into contract and issues wrapping token.
*/
function wrap(address contract_, uint256 tokenId) external virtual override nonReentrant {
require(IERC721(contract_).ownerOf(tokenId) == msg.sender, 'ERC721Wrapper: Caller must own NFT.');
require(IERC721(contract_).getApproved(tokenId) == address(this), 'ERC721Wrapper: Contract must be given approval to wrap NFT.');
require(isWrappable(contract_, tokenId), 'ERC721Wrapper: TokenId not within approved range.');
IERC721(contract_).transferFrom(msg.sender, address(this), tokenId);
_wrap(msg.sender, tokenId);
}
/**
* @dev Burns wrapped token and transfer original back to sender.
*/
function unwrap(address contract_, uint256 tokenId) external virtual override nonReentrant {
require(msg.sender == ownerOf(tokenId), "ERC721Wrapper: Caller does not own wrapped token.");
_burn(tokenId);
IERC721(contract_).safeTransferFrom(address(this), msg.sender, tokenId);
emit Unwrapped(msg.sender, tokenId);
}
/**
* @dev Receives token and mints wrapped token back to sender.
*/
function onERC721Received(address, address from, uint256 tokenId, bytes calldata)
external
virtual
override
nonReentrant
returns (bytes4)
{
require(isWrappable(msg.sender, tokenId), 'ERC721Wrapper: TokenId not within approved range.');
_wrap(from, tokenId);
return this.onERC721Received.selector;
}
/**
* @dev Mints wrapped token.
*/
function _wrap(address to, uint256 tokenId) internal virtual {
_mint(to, tokenId);
emit Wrapped(to, tokenId);
}
/**
* @dev Returns whether the specified tokenId is approved to wrap.
*/
function isWrappable(address contract_, uint256 tokenId) public view virtual override returns (bool) {
return (
_approvedTokenRanges[contract_].maxTokenId != 0 &&
tokenId >= _approvedTokenRanges[contract_].minTokenId &&
tokenId <= _approvedTokenRanges[contract_].maxTokenId
);
}
/**
* @dev See {IERC721Wrapper-updateApprovedTokenRanges}.
*/
function updateApprovedTokenRanges(address contract_, uint256 minTokenId, uint256 maxTokenId) public virtual override;
/**
* @dev Updates approved contract/token ranges. Simple access control mechanism.
*/
function _updateApprovedTokenRanges(address contract_, uint256 minTokenId, uint256 maxTokenId) internal virtual {
require(minTokenId <= maxTokenId, 'ERC721Wrapper: Min tokenId must be less-than/equal to max.');
if (_approvedTokenRanges[contract_].maxTokenId == 0) {
_approvedTokenRanges[contract_] = TokenIdRange(minTokenId, maxTokenId);
} else {
_approvedTokenRanges[contract_].minTokenId = minTokenId;
_approvedTokenRanges[contract_].maxTokenId = maxTokenId;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author jpegmint.xyz
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @dev NiftyBuilder interface stub for IPFS hash method.
*/
interface INiftyBuilder is IERC721 {
/**
* @dev Returns IPFS hash for the tokenId.
*/
function tokenIPFSHash(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
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.0;
/// @author jpegmint.xyz
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
/**
* @title ERC721 token wrapping interface.
*/
interface IERC721Wrapper is IERC721, IERC721Receiver {
/**
* @dev Emitted when `tokenId` token wrapped by `from`.
*/
event Wrapped(address indexed from, uint256 tokenId);
/**
* @dev Emitted when `tokenId` token is unwrapped by `from`.
*/
event Unwrapped(address indexed from, uint256 tokenId);
/**
* @dev Wraps `tokenId` by receiving token and minting matching token.
* Emits a {Wrapped} event.
*/
function wrap(address contract_, uint256 tokenId) external;
/**
* @dev Unwraps `tokenId` by burning wrapped and returning original token.
* Emits a {Unwrapped} event.
*/
function unwrap(address contract_, uint256 tokenId) external;
/**
* @dev Checks and returns whether the tokenId is wrappable.
*/
function isWrappable(address contract_, uint256 tokenId) external view returns (bool);
/**
* @dev Updates and maintains approved contract/tokenIds that contract can wrap.
*/
function updateApprovedTokenRanges(address contract_, uint256 minTokenId, uint256 maxTokenId) external;
}
// 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 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
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);
}
| * _ __ __ ___ __ ___ ___ | | /| / /______ ____ ___ ___ ___/ / / _ )__ _____ / /_ ___ / _/ / _ \___ __ _ ___ |__/|__/_/ \_,_/ .__/ .__/\__/\_,_/ /____/\_,_/___/\__/ \___/_/ /_/|_|\___/_/_/_/\__/ /_/ /_/ @dev Wrapping contract for ROME token to improve the TokenURI metadata./ | contract WrappedBustOfRomeOneYear is ERC721Wrapper, Ownable {
using Strings for uint256;
INiftyBuilder private immutable _niftyBuilderInstance;
constructor(address niftyBuilderAddress) ERC721("Wrapped Bust of Rome (One Year)", "wROME") {
_niftyBuilderInstance = INiftyBuilder(niftyBuilderAddress);
}
function updateApprovedTokenRanges(address contract_, uint256 minTokenId, uint256 maxTokenId) public override onlyOwner {
require(contract_ == address(_niftyBuilderInstance), 'wROME: Can only approve ROME contract tokens.');
_updateApprovedTokenRanges(contract_, minTokenId, maxTokenId);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "wROME: URI query for nonexistent token");
string memory mintNumber = (tokenId - 100010000).toString();
string memory ipfsHash = _niftyBuilderInstance.tokenIPFSHash(tokenId);
string memory arweaveHash = _getTokenArweaveHash(ipfsHash);
bytes memory byteString;
byteString = abi.encodePacked(byteString, 'data:application/json;utf8,{');
byteString = abi.encodePacked(byteString, '"name": "Eroding and Reforming Bust of Rome (One Year) #', mintNumber, '/671",');
byteString = abi.encodePacked(byteString, '"created_by": "Daniel Arsham",');
byteString = abi.encodePacked(byteString
,'"description": "**Daniel Arsham** (b. 1980)\\n\\n'
,'***Eroding and Reforming Bust of Rome (One Year)***, 2021\\n\\n'
,'With his debut NFT release, Daniel Arsham introduces a concept never before seen on Nifty Gateway. '
,'His piece will erode, reform, and change based on the time of year.",'
);
byteString = abi.encodePacked(byteString
);
byteString = abi.encodePacked(byteString, '}');
return string(byteString);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "wROME: URI query for nonexistent token");
string memory mintNumber = (tokenId - 100010000).toString();
string memory ipfsHash = _niftyBuilderInstance.tokenIPFSHash(tokenId);
string memory arweaveHash = _getTokenArweaveHash(ipfsHash);
bytes memory byteString;
byteString = abi.encodePacked(byteString, 'data:application/json;utf8,{');
byteString = abi.encodePacked(byteString, '"name": "Eroding and Reforming Bust of Rome (One Year) #', mintNumber, '/671",');
byteString = abi.encodePacked(byteString, '"created_by": "Daniel Arsham",');
byteString = abi.encodePacked(byteString
,'"description": "**Daniel Arsham** (b. 1980)\\n\\n'
,'***Eroding and Reforming Bust of Rome (One Year)***, 2021\\n\\n'
,'With his debut NFT release, Daniel Arsham introduces a concept never before seen on Nifty Gateway. '
,'His piece will erode, reform, and change based on the time of year.",'
);
byteString = abi.encodePacked(byteString
);
byteString = abi.encodePacked(byteString, '}');
return string(byteString);
}
byteString = abi.encodePacked(byteString, '"attributes":[{"trait_type": "Edition", "display_type": "number", "value": ', mintNumber, ', "max_value": 671}]');
function _getTokenArweaveHash(string memory ipfsHash) private pure returns (string memory) {
bytes32 ipfsMatcher = keccak256(abi.encodePacked(ipfsHash));
revert('wROME: Invalid IPFS hash');
}
function recoverOrphanedToken(uint256 tokenId) external onlyOwner {
require(!_exists(tokenId), "wROME: can't recover wrapped token");
require(_niftyBuilderInstance.ownerOf(tokenId) == address(this), "wROME: can't recover token that is not own");
_niftyBuilderInstance.safeTransferFrom(address(this), msg.sender, tokenId);
}
}
| 14,789,045 | [
1,
67,
1377,
1001,
12900,
1001,
225,
19608,
6647,
1001,
540,
19608,
225,
19608,
571,
571,
342,
96,
342,
342,
7198,
972,
19608,
67,
225,
19608,
225,
19608,
19608,
19,
342,
342,
389,
262,
972,
389,
7198,
342,
342,
67,
225,
19608,
225,
342,
389,
19,
342,
389,
521,
31268,
225,
1001,
389,
225,
19608,
571,
972,
19,
96,
972,
18510,
19,
225,
521,
67,
16,
67,
19,
263,
972,
19,
263,
972,
24441,
972,
24441,
67,
16,
67,
19,
342,
7198,
24441,
67,
16,
67,
19,
31268,
24441,
972,
19,
225,
521,
31268,
18510,
19,
225,
342,
67,
19,
96,
67,
8960,
31268,
18510,
18510,
18510,
24441,
972,
19,
7734,
342,
67,
19,
225,
342,
67,
19,
225,
4266,
1382,
6835,
364,
6525,
958,
1147,
358,
21171,
326,
3155,
3098,
1982,
18,
19,
2,
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,
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
] | [
1,
16351,
24506,
38,
641,
951,
54,
1742,
3335,
5593,
353,
4232,
39,
27,
5340,
3611,
16,
14223,
6914,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
2120,
2136,
93,
1263,
3238,
11732,
389,
82,
2136,
93,
1263,
1442,
31,
203,
203,
203,
203,
565,
3885,
12,
2867,
290,
2136,
93,
1263,
1887,
13,
4232,
39,
27,
5340,
2932,
17665,
605,
641,
434,
534,
1742,
261,
3335,
16666,
2225,
16,
315,
91,
1457,
958,
7923,
288,
203,
3639,
389,
82,
2136,
93,
1263,
1442,
273,
2120,
2136,
93,
1263,
12,
82,
2136,
93,
1263,
1887,
1769,
203,
565,
289,
203,
203,
565,
445,
1089,
31639,
1345,
9932,
12,
2867,
6835,
67,
16,
2254,
5034,
1131,
1345,
548,
16,
2254,
5034,
943,
1345,
548,
13,
1071,
3849,
1338,
5541,
288,
203,
3639,
2583,
12,
16351,
67,
422,
1758,
24899,
82,
2136,
93,
1263,
1442,
3631,
296,
91,
1457,
958,
30,
4480,
1338,
6617,
537,
6525,
958,
6835,
2430,
1093,
1769,
203,
3639,
389,
2725,
31639,
1345,
9932,
12,
16351,
67,
16,
1131,
1345,
548,
16,
943,
1345,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
91,
1457,
958,
30,
3699,
843,
364,
1661,
19041,
1147,
8863,
203,
203,
3639,
533,
3778,
312,
474,
1854,
273,
261,
2316,
548,
300,
2130,
1611,
2787,
2934,
10492,
5621,
203,
3639,
533,
3778,
2359,
2556,
2310,
2
] |
pragma solidity >=0.4.21 <0.7.0;
interface ArbBLS {
// Associate a BLS public key with the caller's address
function register(uint x0, uint x1, uint y0, uint y1) external;
// Get the BLS public key associated with an address (revert if there isn't one)
function getPublicKey(address addr) external view returns (uint, uint, uint, uint);
}
| Associate a BLS public key with the caller's address Get the BLS public key associated with an address (revert if there isn't one) | interface ArbBLS {
function register(uint x0, uint x1, uint y0, uint y1) external;
function getPublicKey(address addr) external view returns (uint, uint, uint, uint);
}
| 12,656,497 | [
1,
23880,
279,
605,
3045,
1071,
498,
598,
326,
4894,
1807,
1758,
968,
326,
605,
3045,
1071,
498,
3627,
598,
392,
1758,
261,
266,
1097,
309,
1915,
5177,
1404,
1245,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
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,
5831,
1201,
70,
38,
3045,
288,
203,
565,
445,
1744,
12,
11890,
619,
20,
16,
2254,
619,
21,
16,
2254,
677,
20,
16,
2254,
677,
21,
13,
3903,
31,
203,
203,
565,
445,
31785,
12,
2867,
3091,
13,
3903,
1476,
1135,
261,
11890,
16,
2254,
16,
2254,
16,
2254,
1769,
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
] |
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "arb-bridge-eth/contracts/bridge/interfaces/IInbox.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../libraries/IWETH9.sol";
import "../../test/TestWETH9.sol";
import "./L1ArbitrumExtendedGateway.sol";
contract L1WethGateway is L1ArbitrumExtendedGateway {
using SafeERC20 for IERC20;
address public l1Weth;
address public l2Weth;
function initialize(
address _l1Counterpart,
address _l1Router,
address _inbox,
address _l1Weth,
address _l2Weth
) public virtual {
L1ArbitrumExtendedGateway._initialize(_l1Counterpart, _l1Router, _inbox);
require(_l1Weth != address(0), "INVALID_L1WETH");
require(_l2Weth != address(0), "INVALID_L2WETH");
l1Weth = _l1Weth;
l2Weth = _l2Weth;
}
function postUpgradeInit() external {}
function createOutboundTx(
address _l1Token,
address _from,
address _to,
uint256 _amount,
uint256 _maxGas,
uint256 _gasPriceBid,
uint256 _maxSubmissionCost,
bytes memory _extraData
) internal virtual override returns (uint256) {
return
sendTxToL2(
_from,
_amount, // send token amount to L2 as call value
_maxSubmissionCost,
_maxGas,
_gasPriceBid,
getOutboundCalldata(_l1Token, _from, _to, _amount, _extraData)
);
}
function sendTxToL2(
address _inbox,
address _to,
address _user,
uint256 _l2CallValue,
uint256 _maxSubmissionCost,
uint256 _maxGas,
uint256 _gasPriceBid,
bytes memory _data
) internal virtual override returns (uint256) {
// msg.value does not include weth withdrawn from user, we need to add in that amount
uint256 seqNum =
IInbox(_inbox).createRetryableTicket{ value: msg.value + _l2CallValue }(
_to,
_l2CallValue,
_maxSubmissionCost,
_user,
_user,
_maxGas,
_gasPriceBid,
_data
);
emit TxToL2(_user, _to, seqNum, _data);
return seqNum;
}
function outboundEscrowTransfer(
address _l1Token,
address _from,
uint256 _amount
) internal virtual override {
IERC20(_l1Token).safeTransferFrom(_from, address(this), _amount);
IWETH9(_l1Token).withdraw(_amount);
}
function inboundEscrowTransfer(
address _l1Token,
address _dest,
uint256 _amount
) internal virtual override {
IWETH9(_l1Token).deposit{ value: _amount }();
IERC20(_l1Token).safeTransfer(_dest, _amount);
}
/**
* @notice Calculate the address used when bridging an ERC20 token
* @dev this always returns the same as the L1 oracle, but may be out of date.
* For example, a custom token may have been registered but not deploy or the contract self destructed.
* @param l1ERC20 address of L1 token
* @return L2 address of a bridged ERC20 token
*/
function _calculateL2TokenAddress(address l1ERC20)
internal
view
virtual
override
returns (address)
{
if (l1ERC20 != l1Weth) {
// invalid L1 weth address
return address(0);
}
return l2Weth;
}
receive() external payable {}
}
| * @notice Calculate the address used when bridging an ERC20 token @dev this always returns the same as the L1 oracle, but may be out of date. For example, a custom token may have been registered but not deploy or the contract self destructed. @param l1ERC20 address of L1 token @return L2 address of a bridged ERC20 token/ invalid L1 weth address | function _calculateL2TokenAddress(address l1ERC20)
internal
view
virtual
override
returns (address)
{
if (l1ERC20 != l1Weth) {
return address(0);
}
return l2Weth;
}
| 12,781,064 | [
1,
8695,
326,
1758,
1399,
1347,
324,
1691,
1998,
392,
4232,
39,
3462,
1147,
225,
333,
3712,
1135,
326,
1967,
487,
326,
511,
21,
20865,
16,
1496,
2026,
506,
596,
434,
1509,
18,
2457,
3454,
16,
279,
1679,
1147,
2026,
1240,
2118,
4104,
1496,
486,
7286,
578,
326,
6835,
365,
23819,
329,
18,
225,
328,
21,
654,
39,
3462,
1758,
434,
511,
21,
1147,
327,
511,
22,
1758,
434,
279,
324,
1691,
2423,
4232,
39,
3462,
1147,
19,
2057,
511,
21,
341,
546,
1758,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
11162,
48,
22,
1345,
1887,
12,
2867,
328,
21,
654,
39,
3462,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1135,
261,
2867,
13,
203,
565,
288,
203,
3639,
309,
261,
80,
21,
654,
39,
3462,
480,
328,
21,
59,
546,
13,
288,
203,
5411,
327,
1758,
12,
20,
1769,
203,
3639,
289,
203,
3639,
327,
328,
22,
59,
546,
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
] |
./partial_match/421613/0xE6Db969E4d0615F1A6071e8F806055662676cEF6/sources/contracts/protocol/libraries/logic/ValidationLogic.sol | * @dev Validates a stable borrow rate rebalance action @param reserve The reserve state on which the user is getting rebalanced @param reserveAddress The address of the reserve @param stableDebtToken The stable debt token instance @param variableDebtToken The variable debt token instance @param zTokenAddress The address of the zToken contract/if the usage ratio is below 95%, no rebalances are neededif the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage,then we allow rebalancing of the stable rate positions. | function validateRebalanceStableBorrowRate(
DataTypes.ReserveData storage reserve,
address reserveAddress,
IERC20 stableDebtToken,
IERC20 variableDebtToken,
address zTokenAddress
) external view {
(bool isActive, , , ) = reserve.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
uint256 totalDebt = stableDebtToken
.totalSupply()
.add(variableDebtToken.totalSupply())
.wadToRay();
uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(zTokenAddress).wadToRay();
uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt));
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 maxVariableBorrowRate = IReserveInterestRateStrategy(
reserve.interestRateStrategyAddress
).getMaxVariableBorrowRate();
require(
usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD &&
currentLiquidityRate <=
maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD),
Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET
);
}
| 16,825,100 | [
1,
9594,
279,
14114,
29759,
4993,
283,
12296,
1301,
225,
20501,
1021,
20501,
919,
603,
1492,
326,
729,
353,
8742,
283,
12296,
72,
225,
20501,
1887,
1021,
1758,
434,
326,
20501,
225,
14114,
758,
23602,
1345,
1021,
14114,
18202,
88,
1147,
791,
225,
2190,
758,
23602,
1345,
1021,
2190,
18202,
88,
1147,
791,
225,
998,
1345,
1887,
1021,
1758,
434,
326,
998,
1345,
6835,
19,
430,
326,
4084,
7169,
353,
5712,
16848,
9,
16,
1158,
283,
70,
26488,
854,
3577,
430,
326,
4501,
372,
24237,
4993,
353,
5712,
2438,
38,
1013,
4722,
67,
3079,
67,
23840,
434,
326,
943,
2190,
432,
8025,
622,
16848,
9,
4084,
16,
15991,
732,
1699,
283,
28867,
434,
326,
14114,
4993,
6865,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
1954,
426,
12296,
30915,
38,
15318,
4727,
12,
203,
565,
1910,
2016,
18,
607,
6527,
751,
2502,
20501,
16,
203,
565,
1758,
20501,
1887,
16,
203,
565,
467,
654,
39,
3462,
14114,
758,
23602,
1345,
16,
203,
565,
467,
654,
39,
3462,
2190,
758,
23602,
1345,
16,
203,
565,
1758,
998,
1345,
1887,
203,
225,
262,
3903,
1476,
288,
203,
565,
261,
6430,
15083,
16,
269,
269,
262,
273,
20501,
18,
7025,
18,
588,
5094,
5621,
203,
203,
565,
2583,
12,
291,
3896,
16,
9372,
18,
58,
48,
67,
3417,
67,
13301,
67,
862,
2123,
3412,
1769,
203,
203,
565,
2254,
5034,
2078,
758,
23602,
273,
14114,
758,
23602,
1345,
203,
1377,
263,
4963,
3088,
1283,
1435,
203,
1377,
263,
1289,
12,
6105,
758,
23602,
1345,
18,
4963,
3088,
1283,
10756,
203,
1377,
263,
91,
361,
774,
54,
528,
5621,
203,
565,
2254,
5034,
2319,
48,
18988,
24237,
273,
467,
654,
39,
3462,
12,
455,
6527,
1887,
2934,
12296,
951,
12,
94,
1345,
1887,
2934,
91,
361,
774,
54,
528,
5621,
203,
565,
2254,
5034,
4084,
8541,
273,
2078,
758,
23602,
422,
374,
692,
374,
294,
2078,
758,
23602,
18,
435,
7244,
12,
5699,
48,
18988,
24237,
18,
1289,
12,
4963,
758,
23602,
10019,
203,
203,
203,
565,
2254,
5034,
783,
48,
18988,
24237,
4727,
273,
20501,
18,
2972,
48,
18988,
24237,
4727,
31,
203,
565,
2254,
5034,
943,
3092,
38,
15318,
4727,
273,
467,
607,
6527,
29281,
4727,
4525,
12,
203,
1377,
20501,
18,
2761,
395,
4727,
4525,
1887,
203,
565,
2
] |
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".
/// @dev Based on OpenZeppelin's Ownable.
contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev Constructor sets the original `owner` of the contract to the sender account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerCandidate() {
require(msg.sender == newOwnerCandidate);
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
}
/// @title Math operations with safety checks
library SafeMath {
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) {
// require(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// require(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);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function toPower2(uint256 a) internal pure returns (uint256) {
return mul(a, a);
}
function sqrt(uint256 a) internal pure returns (uint256) {
uint256 c = (a + 1) / 2;
uint256 b = a;
while (c < b) {
b = c;
c = (a / c + c) / 2;
}
return b;
}
}
/// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20)
contract ERC20 {
uint public totalSupply;
function balanceOf(address _owner) constant public returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title ERC Token Standard #677 Interface (https://github.com/ethereum/EIPs/issues/677)
contract ERC677 is ERC20 {
function transferAndCall(address to, uint value, bytes data) public returns (bool ok);
event TransferAndCall(address indexed from, address indexed to, uint value, bytes data);
}
/// @title ERC223Receiver Interface
/// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223
contract ERC223Receiver {
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok);
}
/// @title Basic ERC20 token contract implementation.
/// @dev Based on OpenZeppelin's StandardToken.
contract BasicToken is ERC20 {
using SafeMath for uint256;
uint256 public totalSupply;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) balances;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve (see NOTE)
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
revert();
}
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 uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @dev Gets the balance of the specified address.
/// @param _owner address The address to query the the balance of.
/// @return uint256 representing the amount owned by the passed address.
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
/// @dev Transfer token to a specified address.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/// @dev Transfer tokens from one address to another.
/// @param _from address The address which you want to send tokens from.
/// @param _to address The address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
}
/// @title Standard677Token implentation, base on https://github.com/ethereum/EIPs/issues/677
contract Standard677Token is ERC677, BasicToken {
/// @dev ERC223 safe token transfer from one address to another
/// @param _to address the address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) {
require(super.transfer(_to, _value)); // do a normal token transfer
TransferAndCall(msg.sender, _to, _value, _data);
//filtering if the target is a contract with bytecode inside it
if (isContract(_to)) return contractFallback(_to, _value, _data);
return true;
}
/// @dev called when transaction target is a contract
/// @param _to address the address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function contractFallback(address _to, uint _value, bytes _data) private returns (bool) {
ERC223Receiver receiver = ERC223Receiver(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
return true;
}
/// @dev check if the address is contract
/// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
/// @param _addr address the address to check
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
}
/// @title Token holder contract.
contract TokenHolder is Ownable {
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) {
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
/// @title Colu Local Network contract.
/// @author Tal Beja.
contract ColuLocalNetwork is Ownable, Standard677Token, TokenHolder {
using SafeMath for uint256;
string public constant name = "Colu Local Network";
string public constant symbol = "CLN";
// Using same decimals value as ETH (makes ETH-CLN conversion much easier).
uint8 public constant decimals = 18;
// States whether token transfers is allowed or not.
// Used during token sale.
bool public isTransferable = false;
event TokensTransferable();
modifier transferable() {
require(msg.sender == owner || isTransferable);
_;
}
/// @dev Creates all tokens and gives them to the owner.
function ColuLocalNetwork(uint256 _totalSupply) public {
totalSupply = _totalSupply;
balances[msg.sender] = totalSupply;
}
/// @dev start transferable mode.
function makeTokensTransferable() external onlyOwner {
if (isTransferable) {
return;
}
isTransferable = true;
TokensTransferable();
}
/// @dev Same ERC20 behavior, but reverts if not transferable.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public transferable returns (bool) {
return super.approve(_spender, _value);
}
/// @dev Same ERC20 behavior, but reverts if not transferable.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public transferable returns (bool) {
return super.transfer(_to, _value);
}
/// @dev Same ERC20 behavior, but reverts if not transferable.
/// @param _from address The address to send tokens from.
/// @param _to address The address to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/// @dev Same ERC677 behavior, but reverts if not transferable.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
/// @param _data bytes data to send to receiver if it is a contract.
function transferAndCall(address _to, uint _value, bytes _data) public transferable returns (bool success) {
return super.transferAndCall(_to, _value, _data);
}
}
/// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier
contract Standard223Receiver is ERC223Receiver {
Tkn tkn;
struct Tkn {
address addr;
address sender; // the transaction caller
uint256 value;
}
bool __isTokenFallback;
modifier tokenPayable {
require(__isTokenFallback);
_;
}
/// @dev Called when the receiver of transfer is contract
/// @param _sender address the address of tokens sender
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {
if (!supportsToken(msg.sender)) {
return false;
}
// Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
// Solution: Remove the the data
tkn = Tkn(msg.sender, _sender, _value);
__isTokenFallback = true;
if (!address(this).delegatecall(_data)) {
__isTokenFallback = false;
return false;
}
// avoid doing an overwrite to .token, which would be more expensive
// makes accessing .tkn values outside tokenPayable functions unsafe
__isTokenFallback = false;
return true;
}
function supportsToken(address token) public constant returns (bool);
}
/// @title TokenOwnable
/// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation
contract TokenOwnable is Standard223Receiver, Ownable {
/// @dev Reverts if called by any account other than the owner for token sending.
modifier onlyTokenOwner() {
require(tkn.sender == owner);
_;
}
}
/// @title Vesting trustee contract for Colu Local Network.
/// @dev This Contract can't be TokenHolder, since it will allow its owner to drain its vested tokens.
/// @dev This means that any token sent to it different than ColuLocalNetwork is basicly stucked here forever.
/// @dev ColuLocalNetwork that sent here (by mistake) can withdrawn using the grant method.
contract VestingTrustee is TokenOwnable {
using SafeMath for uint256;
// Colu Local Network contract.
ColuLocalNetwork public cln;
// Vesting grant for a speicifc holder.
struct Grant {
uint256 value;
uint256 start;
uint256 cliff;
uint256 end;
uint256 installmentLength; // In seconds.
uint256 transferred;
bool revokable;
}
// Holder to grant information mapping.
mapping (address => Grant) public grants;
// Total tokens vested.
uint256 public totalVesting;
event NewGrant(address indexed _from, address indexed _to, uint256 _value);
event TokensUnlocked(address indexed _to, uint256 _value);
event GrantRevoked(address indexed _holder, uint256 _refund);
uint constant OK = 1;
uint constant ERR_INVALID_VALUE = 10001;
uint constant ERR_INVALID_VESTED = 10002;
uint constant ERR_INVALID_TRANSFERABLE = 10003;
event Error(address indexed sender, uint error);
/// @dev Constructor that initializes the address of the Colu Local Network contract.
/// @param _cln ColuLocalNetwork The address of the previously deployed Colu Local Network contract.
function VestingTrustee(ColuLocalNetwork _cln) public {
require(_cln != address(0));
cln = _cln;
}
/// @dev Allow only cln token to be tokenPayable
/// @param token the token to check
function supportsToken(address token) public constant returns (bool) {
return (cln == token);
}
/// @dev Grant tokens to a specified address.
/// @param _to address The holder address.
/// @param _start uint256 The beginning of the vesting period (timestamp).
/// @param _cliff uint256 When the first installment is made (timestamp).
/// @param _end uint256 The end of the vesting period (timestamp).
/// @param _installmentLength uint256 The length of each vesting installment (in seconds).
/// @param _revokable bool Whether the grant is revokable or not.
function grant(address _to, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revokable)
external onlyTokenOwner tokenPayable {
require(_to != address(0));
require(_to != address(this)); // Protect this contract from receiving a grant.
uint256 value = tkn.value;
require(value > 0);
// Require that every holder can be granted tokens only once.
require(grants[_to].value == 0);
// Require for time ranges to be consistent and valid.
require(_start <= _cliff && _cliff <= _end);
// Require installment length to be valid and no longer than (end - start).
require(_installmentLength > 0 && _installmentLength <= _end.sub(_start));
// Grant must not exceed the total amount of tokens currently available for vesting.
require(totalVesting.add(value) <= cln.balanceOf(address(this)));
// Assign a new grant.
grants[_to] = Grant({
value: value,
start: _start,
cliff: _cliff,
end: _end,
installmentLength: _installmentLength,
transferred: 0,
revokable: _revokable
});
// Since tokens have been granted, increase the total amount vested.
totalVesting = totalVesting.add(value);
NewGrant(msg.sender, _to, value);
}
/// @dev Grant tokens to a specified address.
/// @param _to address The holder address.
/// @param _value uint256 The amount of tokens to be granted.
/// @param _start uint256 The beginning of the vesting period (timestamp).
/// @param _cliff uint256 When the first installment is made (timestamp).
/// @param _end uint256 The end of the vesting period (timestamp).
/// @param _installmentLength uint256 The length of each vesting installment (in seconds).
/// @param _revokable bool Whether the grant is revokable or not.
function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revokable)
external onlyOwner {
require(_to != address(0));
require(_to != address(this)); // Protect this contract from receiving a grant.
require(_value > 0);
// Require that every holder can be granted tokens only once.
require(grants[_to].value == 0);
// Require for time ranges to be consistent and valid.
require(_start <= _cliff && _cliff <= _end);
// Require installment length to be valid and no longer than (end - start).
require(_installmentLength > 0 && _installmentLength <= _end.sub(_start));
// Grant must not exceed the total amount of tokens currently available for vesting.
require(totalVesting.add(_value) <= cln.balanceOf(address(this)));
// Assign a new grant.
grants[_to] = Grant({
value: _value,
start: _start,
cliff: _cliff,
end: _end,
installmentLength: _installmentLength,
transferred: 0,
revokable: _revokable
});
// Since tokens have been granted, increase the total amount vested.
totalVesting = totalVesting.add(_value);
NewGrant(msg.sender, _to, _value);
}
/// @dev Revoke the grant of tokens of a specifed address.
/// @dev Unlocked tokens will be sent to the grantee, the rest is transferred to the trustee's owner.
/// @param _holder The address which will have its tokens revoked.
function revoke(address _holder) public onlyOwner {
Grant memory grant = grants[_holder];
// Grant must be revokable.
require(grant.revokable);
// Get the total amount of vested tokens, acccording to grant.
uint256 vested = calculateVestedTokens(grant, now);
// Calculate the untransferred vested tokens.
uint256 transferable = vested.sub(grant.transferred);
if (transferable > 0) {
// Update transferred and total vesting amount, then transfer remaining vested funds to holder.
grant.transferred = grant.transferred.add(transferable);
totalVesting = totalVesting.sub(transferable);
require(cln.transfer(_holder, transferable));
TokensUnlocked(_holder, transferable);
}
// Calculate amount of remaining tokens that can still be returned.
uint256 refund = grant.value.sub(grant.transferred);
// Remove the grant.
delete grants[_holder];
// Update total vesting amount and transfer previously calculated tokens to owner.
totalVesting = totalVesting.sub(refund);
require(cln.transfer(msg.sender, refund));
GrantRevoked(_holder, refund);
}
/// @dev Calculate the amount of ready tokens of a holder.
/// @param _holder address The address of the holder.
/// @return a uint256 Representing a holder's total amount of vested tokens.
function readyTokens(address _holder) public constant returns (uint256) {
Grant memory grant = grants[_holder];
if (grant.value == 0) {
return 0;
}
uint256 vested = calculateVestedTokens(grant, now);
if (vested == 0) {
return 0;
}
return vested.sub(grant.transferred);
}
/// @dev Calculate the total amount of vested tokens of a holder at a given time.
/// @param _holder address The address of the holder.
/// @param _time uint256 The specific time to calculate against.
/// @return a uint256 Representing a holder's total amount of vested tokens.
function vestedTokens(address _holder, uint256 _time) public constant returns (uint256) {
Grant memory grant = grants[_holder];
if (grant.value == 0) {
return 0;
}
return calculateVestedTokens(grant, _time);
}
/// @dev Calculate amount of vested tokens at a specifc time.
/// @param _grant Grant The vesting grant.
/// @param _time uint256 The time to be checked
/// @return An uint256 Representing the amount of vested tokens of a specific grant.
function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) {
// If we're before the cliff, then nothing is vested.
if (_time < _grant.cliff) {
return 0;
}
// If we're after the end of the vesting period - everything is vested.
if (_time >= _grant.end) {
return _grant.value;
}
// Calculate amount of installments past until now.
//
// NOTE: result gets floored because of integer division.
uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength);
// Calculate amount of days in entire vesting period.
uint256 vestingDays = _grant.end.sub(_grant.start);
// Calculate and return the number of tokens according to vesting days that have passed.
return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays);
}
/// @dev Unlock vested tokens and transfer them to the grantee.
/// @return a uint The success or error code.
function unlockVestedTokens() external returns (uint) {
return unlockVestedTokens(msg.sender);
}
/// @dev Unlock vested tokens and transfer them to the grantee (helper function).
/// @param _grantee address The address of the grantee.
/// @return a uint The success or error code.
function unlockVestedTokens(address _grantee) private returns (uint) {
Grant storage grant = grants[_grantee];
// Make sure the grant has tokens available.
if (grant.value == 0) {
Error(_grantee, ERR_INVALID_VALUE);
return ERR_INVALID_VALUE;
}
// Get the total amount of vested tokens, acccording to grant.
uint256 vested = calculateVestedTokens(grant, now);
if (vested == 0) {
Error(_grantee, ERR_INVALID_VESTED);
return ERR_INVALID_VESTED;
}
// Make sure the holder doesn't transfer more than what he already has.
uint256 transferable = vested.sub(grant.transferred);
if (transferable == 0) {
Error(_grantee, ERR_INVALID_TRANSFERABLE);
return ERR_INVALID_TRANSFERABLE;
}
// Update transferred and total vesting amount, then transfer remaining vested funds to holder.
grant.transferred = grant.transferred.add(transferable);
totalVesting = totalVesting.sub(transferable);
require(cln.transfer(_grantee, transferable));
TokensUnlocked(_grantee, transferable);
return OK;
}
/// @dev batchUnlockVestedTokens vested tokens and transfer them to the grantees.
/// @param _grantees address[] The addresses of the grantees.
/// @return a boo if success.
function batchUnlockVestedTokens(address[] _grantees) external onlyOwner returns (bool success) {
for (uint i = 0; i<_grantees.length; i++) {
unlockVestedTokens(_grantees[i]);
}
return true;
}
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function withdrawERC20(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) {
if (_tokenAddress == address(cln)) {
// If the token is cln, allow to withdraw only non vested tokens.
uint256 availableCLN = cln.balanceOf(this).sub(totalVesting);
require(_amount <= availableCLN);
}
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
/// @title Colu Local Network sale contract.
/// @author Tal Beja.
contract ColuLocalNetworkSale is Ownable, TokenHolder {
using SafeMath for uint256;
// External parties:
// Colu Local Network contract.
ColuLocalNetwork public cln;
// Vesting contract for presale participants.
VestingTrustee public trustee;
// Received funds are forwarded to this address.
address public fundingRecipient;
// Post-TDE multisig addresses.
address public communityPoolAddress;
address public futureDevelopmentPoolAddress;
address public stakeholdersPoolAddress;
// Colu Local Network decimals.
// Using same decimals value as ETH (makes ETH-CLN conversion much easier).
// This is the same as in Colu Local Network contract.
uint256 public constant TOKEN_DECIMALS = 10 ** 18;
// Additional Lockup Allocation Pool
uint256 public constant ALAP = 40701333592592592592614116;
// Maximum number of tokens in circulation: 1.5 trillion.
uint256 public constant MAX_TOKENS = 15 * 10 ** 8 * TOKEN_DECIMALS + ALAP;
// Maximum tokens offered in the sale (35%) + ALAP.
uint256 public constant MAX_TOKENS_SOLD = 525 * 10 ** 6 * TOKEN_DECIMALS + ALAP;
// Maximum tokens offered in the presale (from the initial 35% offered tokens) + ALAP.
uint256 public constant MAX_PRESALE_TOKENS_SOLD = 2625 * 10 ** 5 * TOKEN_DECIMALS + ALAP;
// Tokens allocated for Community pool (30%).
uint256 public constant COMMUNITY_POOL = 45 * 10 ** 7 * TOKEN_DECIMALS;
// Tokens allocated for Future development pool (29%).
uint256 public constant FUTURE_DEVELOPMENT_POOL = 435 * 10 ** 6 * TOKEN_DECIMALS;
// Tokens allocated for Stakeholdes pool (6%).
uint256 public constant STAKEHOLDERS_POOL = 9 * 10 ** 7 * TOKEN_DECIMALS;
// CLN to ETH ratio.
uint256 public constant CLN_PER_ETH = 8600;
// Sale start, end blocks (time ranges)
uint256 public constant SALE_DURATION = 4 days;
uint256 public startTime;
uint256 public endTime;
// Amount of tokens sold until now in the sale.
uint256 public tokensSold = 0;
// Amount of tokens sold until now in the presale.
uint256 public presaleTokensSold = 0;
// Accumulated amount each participant has contributed so far in the sale (in WEI).
mapping (address => uint256) public participationHistory;
// Accumulated amount each participant have contributed so far in the presale.
mapping (address => uint256) public participationPresaleHistory;
// Maximum amount that each particular is allowed to contribute (in ETH-WEI).
// Defaults to zero. Serving as a functional whitelist.
mapping (address => uint256) public participationCaps;
// Maximum amount ANYONE is currently allowed to contribute. Set to max uint256 so no limitation other than personal participationCaps.
uint256 public hardParticipationCap = uint256(-1);
// initialization of the contract, splitted from the constructor to avoid gas block limit.
bool public initialized = false;
// Vesting plan structure for presale
struct VestingPlan {
uint256 startOffset;
uint256 cliffOffset;
uint256 endOffset;
uint256 installmentLength;
uint8 alapPercent;
}
// Vesting plans for presale
VestingPlan[] public vestingPlans;
// Each token that is sent from the ColuLocalNetworkSale is considered as issued.
event TokensIssued(address indexed to, uint256 tokens);
/// @dev Reverts if called not before the sale.
modifier onlyBeforeSale() {
if (now >= startTime) {
revert();
}
_;
}
/// @dev Reverts if called not during the sale.
modifier onlyDuringSale() {
if (tokensSold >= MAX_TOKENS_SOLD || now < startTime || now >= endTime) {
revert();
}
_;
}
/// @dev Reverts if called before the sale ends.
modifier onlyAfterSale() {
if (!(tokensSold >= MAX_TOKENS_SOLD || now >= endTime)) {
revert();
}
_;
}
/// @dev Reverts if called before the sale is initialized.
modifier notInitialized() {
if (initialized) {
revert();
}
_;
}
/// @dev Reverts if called after the sale is initialized.
modifier isInitialized() {
if (!initialized) {
revert();
}
_;
}
/// @dev Constructor sets the sale addresses and start time.
/// @param _owner address The address of this contract owner.
/// @param _fundingRecipient address The address of the funding recipient.
/// @param _communityPoolAddress address The address of the community pool.
/// @param _futureDevelopmentPoolAddress address The address of the future development pool.
/// @param _stakeholdersPoolAddress address The address of the team pool.
/// @param _startTime uint256 The start time of the token sale.
function ColuLocalNetworkSale(address _owner,
address _fundingRecipient,
address _communityPoolAddress,
address _futureDevelopmentPoolAddress,
address _stakeholdersPoolAddress,
uint256 _startTime) public {
require(_owner != address(0));
require(_fundingRecipient != address(0));
require(_communityPoolAddress != address(0));
require(_futureDevelopmentPoolAddress != address(0));
require(_stakeholdersPoolAddress != address(0));
require(_startTime > now);
owner = _owner;
fundingRecipient = _fundingRecipient;
communityPoolAddress = _communityPoolAddress;
futureDevelopmentPoolAddress = _futureDevelopmentPoolAddress;
stakeholdersPoolAddress = _stakeholdersPoolAddress;
startTime = _startTime;
endTime = startTime + SALE_DURATION;
}
/// @dev Initialize the sale conditions.
function initialize() public onlyOwner notInitialized {
initialized = true;
uint256 months = 1 years / 12;
vestingPlans.push(VestingPlan(0, 0, 1, 1, 0));
vestingPlans.push(VestingPlan(0, 0, 6 * months, 1 * months, 4));
vestingPlans.push(VestingPlan(0, 0, 1 years, 1 * months, 12));
vestingPlans.push(VestingPlan(0, 0, 2 years, 1 * months, 26));
vestingPlans.push(VestingPlan(0, 0, 3 years, 1 * months, 35));
// Deploy new ColuLocalNetwork contract.
cln = new ColuLocalNetwork(MAX_TOKENS);
// Deploy new VestingTrustee contract.
trustee = new VestingTrustee(cln);
// allocate pool tokens:
// Issue the remaining tokens to designated pools.
require(transferTokens(communityPoolAddress, COMMUNITY_POOL));
// stakeholdersPoolAddress will create its own vesting trusts.
require(transferTokens(stakeholdersPoolAddress, STAKEHOLDERS_POOL));
}
/// @dev Allocate tokens to presale participant according to its vesting plan and invesment value.
/// @param _recipient address The presale participant address to recieve the tokens.
/// @param _etherValue uint256 The invesment value (in ETH).
/// @param _vestingPlanIndex uint8 The vesting plan index.
function presaleAllocation(address _recipient, uint256 _etherValue, uint8 _vestingPlanIndex) external onlyOwner onlyBeforeSale isInitialized {
require(_recipient != address(0));
require(_vestingPlanIndex < vestingPlans.length);
// Calculate plan and token amount.
VestingPlan memory plan = vestingPlans[_vestingPlanIndex];
uint256 tokensAndALAPPerEth = CLN_PER_ETH.mul(SafeMath.add(100, plan.alapPercent)).div(100);
uint256 tokensLeftInPreSale = MAX_PRESALE_TOKENS_SOLD.sub(presaleTokensSold);
uint256 weiLeftInSale = tokensLeftInPreSale.div(tokensAndALAPPerEth);
uint256 weiToParticipate = SafeMath.min256(_etherValue, weiLeftInSale);
require(weiToParticipate > 0);
participationPresaleHistory[msg.sender] = participationPresaleHistory[msg.sender].add(weiToParticipate);
uint256 tokensToTransfer = weiToParticipate.mul(tokensAndALAPPerEth);
presaleTokensSold = presaleTokensSold.add(tokensToTransfer);
tokensSold = tokensSold.add(tokensToTransfer);
// Transfer tokens to trustee and create grant.
grant(_recipient, tokensToTransfer, startTime.add(plan.startOffset), startTime.add(plan.cliffOffset),
startTime.add(plan.endOffset), plan.installmentLength, false);
}
/// @dev Add a list of participants to a capped participation tier.
/// @param _participants address[] The list of participant addresses.
/// @param _cap uint256 The cap amount (in ETH-WEI).
function setParticipationCap(address[] _participants, uint256 _cap) external onlyOwner isInitialized {
for (uint i = 0; i < _participants.length; i++) {
participationCaps[_participants[i]] = _cap;
}
}
/// @dev Set hard participation cap for all participants.
/// @param _cap uint256 The hard cap amount.
function setHardParticipationCap(uint256 _cap) external onlyOwner isInitialized {
require(_cap > 0);
hardParticipationCap = _cap;
}
/// @dev Fallback function that will delegate the request to participate().
function () external payable onlyDuringSale isInitialized {
participate(msg.sender);
}
/// @dev Create and sell tokens to the caller.
/// @param _recipient address The address of the recipient receiving the tokens.
function participate(address _recipient) public payable onlyDuringSale isInitialized {
require(_recipient != address(0));
// Enforce participation cap (in WEI received).
uint256 weiAlreadyParticipated = participationHistory[_recipient];
uint256 participationCap = SafeMath.min256(participationCaps[_recipient], hardParticipationCap);
uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated));
require(cappedWeiReceived > 0);
// Accept funds and transfer to funding recipient.
uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold);
uint256 weiLeftInSale = tokensLeftInSale.div(CLN_PER_ETH);
uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale);
participationHistory[_recipient] = weiAlreadyParticipated.add(weiToParticipate);
fundingRecipient.transfer(weiToParticipate);
// Transfer tokens to recipient.
uint256 tokensToTransfer = weiToParticipate.mul(CLN_PER_ETH);
if (tokensLeftInSale.sub(tokensToTransfer) < CLN_PER_ETH) {
// If purchase would cause less than CLN_PER_ETH tokens to be left then nobody could ever buy them.
// So, gift them to the last buyer.
tokensToTransfer = tokensLeftInSale;
}
tokensSold = tokensSold.add(tokensToTransfer);
require(transferTokens(_recipient, tokensToTransfer));
// Partial refund if full participation not possible
// e.g. due to cap being reached.
uint256 refund = msg.value.sub(weiToParticipate);
if (refund > 0) {
msg.sender.transfer(refund);
}
}
/// @dev Finalizes the token sale event: make future development pool grant (lockup) and make token transfarable.
function finalize() external onlyAfterSale onlyOwner isInitialized {
if (cln.isTransferable()) {
revert();
}
// Add unsold token to the future development pool grant (lockup).
uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold);
uint256 futureDevelopmentPool = FUTURE_DEVELOPMENT_POOL.add(tokensLeftInSale);
// Future Development Pool is locked for 3 years.
grant(futureDevelopmentPoolAddress, futureDevelopmentPool, startTime, startTime.add(3 years),
startTime.add(3 years), 1 days, false);
// Make tokens Transferable, end the sale!.
cln.makeTokensTransferable();
}
function grant(address _grantee, uint256 _amount, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revokable) private {
// bytes4 grantSig = bytes4(keccak256("grant(address,uint256,uint256,uint256,uint256,bool)"));
bytes4 grantSig = 0x5ee7e96d;
// 6 arguments of size 32
uint256 argsSize = 6 * 32;
// sig + arguments size
uint256 dataSize = 4 + argsSize;
bytes memory m_data = new bytes(dataSize);
assembly {
// Add the signature first to memory
mstore(add(m_data, 0x20), grantSig)
// Add the parameters
mstore(add(m_data, 0x24), _grantee)
mstore(add(m_data, 0x44), _start)
mstore(add(m_data, 0x64), _cliff)
mstore(add(m_data, 0x84), _end)
mstore(add(m_data, 0xa4), _installmentLength)
mstore(add(m_data, 0xc4), _revokable)
}
require(transferTokens(trustee, _amount, m_data));
}
/// @dev Transfer tokens from the sale contract to a recipient.
/// @param _recipient address The address of the recipient.
/// @param _tokens uint256 The amount of tokens to transfer.
function transferTokens(address _recipient, uint256 _tokens) private returns (bool ans) {
ans = cln.transfer(_recipient, _tokens);
if (ans) {
TokensIssued(_recipient, _tokens);
}
}
/// @dev Transfer tokens from the sale contract to a recipient.
/// @param _recipient address The address of the recipient.
/// @param _tokens uint256 The amount of tokens to transfer.
/// @param _data bytes data to send to receiver if it is a contract.
function transferTokens(address _recipient, uint256 _tokens, bytes _data) private returns (bool ans) {
// Request Colu Local Network contract to transfer the requested tokens for the buyer.
ans = cln.transferAndCall(_recipient, _tokens, _data);
if (ans) {
TokensIssued(_recipient, _tokens);
}
}
/// @dev Requests to transfer control of the Colu Local Network contract to a new owner.
/// @param _newOwnerCandidate address The address to transfer ownership to.
///
/// NOTE:
/// 1. The new owner will need to call Colu Local Network contract's acceptOwnership directly in order to accept the ownership.
/// 2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of
/// the Colu Local Network contract can transfer tokens during the sale.
function requestColuLocalNetworkOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
cln.requestOwnershipTransfer(_newOwnerCandidate);
}
/// @dev Accepts new ownership on behalf of the Colu Local Network contract.
// This can be used by the sale contract itself to claim back ownership of the Colu Local Network contract.
function acceptColuLocalNetworkOwnership() external onlyOwner {
cln.acceptOwnership();
}
/// @dev Requests to transfer control of the VestingTrustee contract to a new owner.
/// @param _newOwnerCandidate address The address to transfer ownership to.
///
/// NOTE:
/// 1. The new owner will need to call trustee contract's acceptOwnership directly in order to accept the ownership.
/// 2. Calling this method during the token sale will prevent the token sale from alocation presale grunts add finalize, since only the owner of
/// the trustee contract can create grunts needed in the presaleAlocation add finalize methods.
function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
trustee.requestOwnershipTransfer(_newOwnerCandidate);
}
/// @dev Accepts new ownership on behalf of the VestingTrustee contract.
/// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract.
function acceptVestingTrusteeOwnership() external onlyOwner {
trustee.acceptOwnership();
}
} | bytes4 grantSig = bytes4(keccak256("grant(address,uint256,uint256,uint256,uint256,bool)")); 6 arguments of size 32 sig + arguments size Add the signature first to memory Add the parameters | function grant(address _grantee, uint256 _amount, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revokable) private {
bytes4 grantSig = 0x5ee7e96d;
uint256 argsSize = 6 * 32;
uint256 dataSize = 4 + argsSize;
bytes memory m_data = new bytes(dataSize);
assembly {
mstore(add(m_data, 0x20), grantSig)
mstore(add(m_data, 0x24), _grantee)
mstore(add(m_data, 0x44), _start)
mstore(add(m_data, 0x64), _cliff)
mstore(add(m_data, 0x84), _end)
mstore(add(m_data, 0xa4), _installmentLength)
mstore(add(m_data, 0xc4), _revokable)
}
require(transferTokens(trustee, _amount, m_data));
}
| 1,083,172 | [
1,
3890,
24,
7936,
8267,
273,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
16243,
12,
2867,
16,
11890,
5034,
16,
11890,
5034,
16,
11890,
5034,
16,
11890,
5034,
16,
6430,
2225,
10019,
1666,
1775,
434,
963,
3847,
3553,
397,
1775,
963,
1436,
326,
3372,
1122,
358,
3778,
1436,
326,
1472,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7936,
12,
2867,
389,
75,
2450,
22579,
16,
2254,
5034,
389,
8949,
16,
2254,
5034,
389,
1937,
16,
2254,
5034,
389,
830,
3048,
16,
2254,
5034,
389,
409,
16,
203,
3639,
2254,
5034,
389,
5425,
475,
1782,
16,
1426,
389,
9083,
601,
429,
13,
3238,
288,
203,
3639,
1731,
24,
7936,
8267,
273,
374,
92,
25,
1340,
27,
73,
10525,
72,
31,
203,
3639,
2254,
5034,
833,
1225,
273,
1666,
380,
3847,
31,
203,
3639,
2254,
5034,
30216,
273,
1059,
397,
833,
1225,
31,
203,
203,
3639,
1731,
3778,
312,
67,
892,
273,
394,
1731,
12,
892,
1225,
1769,
203,
203,
3639,
19931,
288,
203,
5411,
312,
2233,
12,
1289,
12,
81,
67,
892,
16,
374,
92,
3462,
3631,
7936,
8267,
13,
203,
5411,
312,
2233,
12,
1289,
12,
81,
67,
892,
16,
374,
92,
3247,
3631,
389,
75,
2450,
22579,
13,
203,
5411,
312,
2233,
12,
1289,
12,
81,
67,
892,
16,
374,
92,
6334,
3631,
389,
1937,
13,
203,
5411,
312,
2233,
12,
1289,
12,
81,
67,
892,
16,
374,
92,
1105,
3631,
389,
830,
3048,
13,
203,
5411,
312,
2233,
12,
1289,
12,
81,
67,
892,
16,
374,
92,
5193,
3631,
389,
409,
13,
203,
5411,
312,
2233,
12,
1289,
12,
81,
67,
892,
16,
374,
6995,
24,
3631,
389,
5425,
475,
1782,
13,
203,
5411,
312,
2233,
12,
1289,
12,
81,
67,
892,
16,
374,
6511,
24,
3631,
389,
9083,
601,
429,
13,
203,
3639,
289,
203,
203,
3639,
2583,
12,
13866,
5157,
12,
21879,
1340,
16,
389,
2
] |
./full_match/4/0x42622B6c7f15430722D62eDb45938D91FC27419B/sources/contracts/AllocationStakingV2.sol | Emit relevant event | emit Deposit(msg.sender, _pid, depositAmount);
| 12,286,905 | [
1,
17982,
9368,
871,
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,
0
] | [
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,
0
] | [
1,
3639,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
389,
6610,
16,
443,
1724,
6275,
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
] |
./full_match/1/0xc9E77ef4a304B39bEa702b882E701b757dCd3730/sources/home/paras/roaring-leaders/contracts/RoaringRoccstars.sol | Breed Roaring Leaders via the marketplace. One of the Leaders is owned by "renter", who is paid a fee by the caller/ | function breedUsingMarketplace(uint256 maleTokenId, uint256 femaleTokenId, bool hasSignature, bool instantCooldown, address renter, bool acceptorIsMaleOwner, uint256 rentalFee, uint256 expiry, bytes memory cooldownSignature, bytes memory listingSignature) public {
require(breedingIsActive, "Breeding not live");
breedingManagerContractInstance.breedUsingMarketplace(msg.sender, maleTokenId, femaleTokenId, hasSignature, instantCooldown, renter, acceptorIsMaleOwner, rentalFee, expiry, cooldownSignature, listingSignature);
roarTokenContractInstance.burnFrom(msg.sender, (mintRoarPrice + (instantCooldown ? cooldownPillPrice : 0)) * (hasSignature ? signatureMultiplier : 1) * 10 ** 18);
roarTokenContractInstance.transferFrom(msg.sender, renter, rentalFee * 10 ** 18);
_tokenIdCounter.increment();
_safeMint(msg.sender, _tokenIdCounter.current());
emit CubBornViaMarketplace(_tokenIdCounter.current(), maleTokenId, femaleTokenId, hasSignature, instantCooldown, renter, acceptorIsMaleOwner, rentalFee, expiry);
}
| 4,982,856 | [
1,
38,
15656,
534,
83,
5968,
511,
684,
414,
3970,
326,
29917,
18,
6942,
434,
326,
511,
684,
414,
353,
16199,
635,
315,
1187,
387,
3113,
10354,
353,
30591,
279,
14036,
635,
326,
4894,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
324,
15656,
7736,
3882,
24577,
12,
11890,
5034,
312,
5349,
1345,
548,
16,
2254,
5034,
284,
351,
5349,
1345,
548,
16,
1426,
711,
5374,
16,
1426,
5934,
39,
1371,
2378,
16,
1758,
1654,
387,
16,
1426,
2791,
280,
2520,
49,
5349,
5541,
16,
2254,
5034,
283,
496,
287,
14667,
16,
2254,
5034,
10839,
16,
1731,
3778,
27367,
2378,
5374,
16,
1731,
3778,
11591,
5374,
13,
1071,
288,
203,
3639,
2583,
12,
6073,
329,
310,
2520,
3896,
16,
315,
38,
15656,
310,
486,
8429,
8863,
203,
540,
203,
3639,
324,
15656,
310,
1318,
8924,
1442,
18,
6073,
329,
7736,
3882,
24577,
12,
3576,
18,
15330,
16,
312,
5349,
1345,
548,
16,
284,
351,
5349,
1345,
548,
16,
711,
5374,
16,
5934,
39,
1371,
2378,
16,
1654,
387,
16,
2791,
280,
2520,
49,
5349,
5541,
16,
283,
496,
287,
14667,
16,
10839,
16,
27367,
2378,
5374,
16,
11591,
5374,
1769,
203,
203,
3639,
721,
297,
1345,
8924,
1442,
18,
70,
321,
1265,
12,
3576,
18,
15330,
16,
261,
81,
474,
22869,
297,
5147,
397,
261,
24628,
39,
1371,
2378,
692,
27367,
2378,
52,
737,
5147,
294,
374,
3719,
380,
261,
5332,
5374,
692,
3372,
23365,
294,
404,
13,
380,
1728,
2826,
6549,
1769,
203,
3639,
721,
297,
1345,
8924,
1442,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1654,
387,
16,
283,
496,
287,
14667,
380,
1728,
2826,
6549,
1769,
203,
540,
203,
3639,
389,
2316,
548,
4789,
18,
15016,
5621,
203,
3639,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
389,
2316,
2
] |
./full_match/44787/0x31aa5951100e11b8A34Bc9D98a44De152Dc5d3a2/sources/contracts/vm/ops/math/FixedPointMathOps.sol | @dev Number of provided opcodes for `FixedPointMathOps`. | uint256 constant FIXED_POINT_MATH_OPS_LENGTH = 7;
| 13,256,109 | [
1,
1854,
434,
2112,
1061,
7000,
364,
1375,
7505,
2148,
10477,
8132,
8338,
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,
11890,
5034,
5381,
26585,
67,
8941,
67,
49,
3275,
67,
3665,
55,
67,
7096,
273,
2371,
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
] |
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPool.sol";
import "../cover/Quotation.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "./MCR.sol";
contract Pool is IPool, MasterAware, ReentrancyGuard {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
struct AssetData {
uint112 minAmount;
uint112 maxAmount;
uint32 lastSwapTime;
// 18 decimals of precision. 0.01% -> 0.0001 -> 1e14
uint maxSlippageRatio;
}
/* storage */
address[] public assets;
mapping(address => AssetData) public assetData;
// contracts
Quotation public quotation;
NXMToken public nxmToken;
TokenController public tokenController;
MCR public mcr;
// parameters
address public swapController;
uint public minPoolEth;
PriceFeedOracle public priceFeedOracle;
address public swapOperator;
/* constants */
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant MCR_RATIO_DECIMALS = 4;
uint public constant MAX_MCR_RATIO = 40000; // 400%
uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points
uint internal constant CONSTANT_C = 5800000;
uint internal constant CONSTANT_A = 1028 * 1e13;
uint internal constant TOKEN_EXPONENT = 4;
/* events */
event Payout(address indexed to, address indexed asset, uint amount);
event NXMSold (address indexed member, uint nxmIn, uint ethOut);
event NXMBought (address indexed member, uint ethIn, uint nxmOut);
event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut);
/* logic */
modifier onlySwapOperator {
require(msg.sender == swapOperator, "Pool: not swapOperator");
_;
}
constructor (
address[] memory _assets,
uint112[] memory _minAmounts,
uint112[] memory _maxAmounts,
uint[] memory _maxSlippageRatios,
address _master,
address _priceOracle,
address _swapOperator
) public {
require(_assets.length == _minAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch");
for (uint i = 0; i < _assets.length; i++) {
address asset = _assets[i];
require(asset != address(0), "Pool: asset is zero address");
require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min");
require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min");
assets.push(asset);
assetData[asset].minAmount = _minAmounts[i];
assetData[asset].maxAmount = _maxAmounts[i];
assetData[asset].maxSlippageRatio = _maxSlippageRatios[i];
}
master = INXMMaster(_master);
priceFeedOracle = PriceFeedOracle(_priceOracle);
swapOperator = _swapOperator;
}
// fallback function
function() external payable {}
// for legacy Pool1 upgrade compatibility
function sendEther() external payable {}
/**
* @dev Calculates total value of all pool assets in ether
*/
function getPoolValueInEth() public view returns (uint) {
uint total = address(this).balance;
for (uint i = 0; i < assets.length; i++) {
address assetAddress = assets[i];
IERC20 token = IERC20(assetAddress);
uint rate = priceFeedOracle.getAssetToEthRate(assetAddress);
require(rate > 0, "Pool: zero rate");
uint assetBalance = token.balanceOf(address(this));
uint assetValue = assetBalance.mul(rate).div(1e18);
total = total.add(assetValue);
}
return total;
}
/* asset related functions */
function getAssets() external view returns (address[] memory) {
return assets;
}
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
) {
AssetData memory data = assetData[_asset];
return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio);
}
function addAsset(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_asset != address(0), "Pool: asset is zero address");
require(_max >= _min, "Pool: max < min");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
require(_asset != assets[i], "Pool: asset exists");
}
assets.push(_asset);
assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio);
}
function removeAsset(address _asset) external onlyGovernance {
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
delete assetData[_asset];
assets[i] = assets[assets.length - 1];
assets.pop();
return;
}
revert("Pool: asset not found");
}
function setAssetDetails(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_min <= _max, "Pool: min > max");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
assetData[_asset].minAmount = _min;
assetData[_asset].maxAmount = _max;
assetData[_asset].maxSlippageRatio = _maxSlippageRatio;
return;
}
revert("Pool: asset not found");
}
/* claim related functions */
/**
* @dev Execute the payout in case a claim is accepted
* @param asset token address or 0xEee...EEeE for ether
* @param payoutAddress send funds to this address
* @param amount amount to send
*/
function sendClaimPayout (
address asset,
address payable payoutAddress,
uint amount
) external onlyInternal nonReentrant returns (bool success) {
bool ok;
if (asset == ETH) {
// solhint-disable-next-line avoid-low-level-calls
(ok, /* data */) = payoutAddress.call.value(amount)("");
} else {
ok = _safeTokenTransfer(asset, payoutAddress, amount);
}
if (ok) {
emit Payout(payoutAddress, asset, amount);
}
return ok;
}
/**
* @dev safeTransfer implementation that does not revert
* @param tokenAddress ERC20 address
* @param to destination
* @param value amount to send
* @return success true if the transfer was successfull
*/
function _safeTokenTransfer (
address tokenAddress,
address to,
uint256 value
) internal returns (bool) {
// token address is not a contract
if (!tokenAddress.isContract()) {
return false;
}
IERC20 token = IERC20(tokenAddress);
bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = tokenAddress.call(data);
// low-level call failed/reverted
if (!success) {
return false;
}
// tokens that don't have return data
if (returndata.length == 0) {
return true;
}
// tokens that have return data will return a bool
return abi.decode(returndata, (bool));
}
/* pool lifecycle functions */
function transferAsset(
address asset,
address payable destination,
uint amount
) external onlyGovernance nonReentrant {
require(assetData[asset].maxAmount == 0, "Pool: max not zero");
require(destination != address(0), "Pool: dest zero");
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferableAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferableAmount);
}
function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant {
// transfer ether
uint ethBalance = address(this).balance;
(bool ok, /* data */) = newPoolAddress.call.value(ethBalance)("");
require(ok, "Pool: transfer failed");
// transfer assets
for (uint i = 0; i < assets.length; i++) {
IERC20 token = IERC20(assets[i]);
uint tokenBalance = token.balanceOf(address(this));
token.safeTransfer(newPoolAddress, tokenBalance);
}
}
/**
* @dev Update dependent contract address
* @dev Implements MasterAware interface function
*/
function changeDependentContractAddress() public {
nxmToken = NXMToken(master.tokenAddress());
tokenController = TokenController(master.getLatestAddress("TC"));
quotation = Quotation(master.getLatestAddress("QT"));
mcr = MCR(master.getLatestAddress("MC"));
}
/* cover purchase functions */
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable onlyMember whenNotPaused {
require(coverCurr == "ETH", "Pool: Unexpected asset type");
require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyMember whenNotPaused {
require(coverCurr != "ETH", "Pool: Unexpected asset type");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused {
IERC20 token = IERC20(asset);
token.safeTransferFrom(from, address(this), amount);
}
function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused {
if (asset == ETH) {
(bool ok, /* data */) = swapOperator.call.value(amount)("");
require(ok, "Pool: Eth transfer failed");
return;
}
IERC20 token = IERC20(asset);
token.safeTransfer(swapOperator, amount);
}
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused {
assetData[asset].lastSwapTime = lastSwapTime;
}
/* token sale functions */
/**
* @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) {
sellNXM(_amount, 0);
return true;
}
/**
* @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) external view returns (uint weiToPay) {
return getEthForNXM(amount);
}
/**
* @dev Buys NXM tokens with ETH.
* @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number.
* @return boughtTokens number of bought tokens.
*/
function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused {
uint ethIn = msg.value;
require(ethIn > 0, "Pool: ethIn > 0");
uint totalAssetValue = getPoolValueInEth().sub(ethIn);
uint mcrEth = mcr.getMCR();
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%");
uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth);
require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut");
tokenController.mint(msg.sender, tokensOut);
// evaluate the new MCR for the current asset value including the ETH paid in
mcr.updateMCRInternal(totalAssetValue.add(ethIn), false);
emit NXMBought(msg.sender, ethIn, tokensOut);
}
/**
* @dev Sell NXM tokens and receive ETH.
* @param tokenAmount Amount of tokens to sell.
* @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number.
* @return ethOut amount of ETH received in exchange for the tokens.
*/
function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused {
require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance");
require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting");
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth);
require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%");
require(ethOut >= minEthOut, "Pool: ethOut < minEthOut");
tokenController.burnFrom(msg.sender, tokenAmount);
(bool ok, /* data */) = msg.sender.call.value(ethOut)("");
require(ok, "Pool: Sell transfer failed");
// evaluate the new MCR for the current asset value excluding the paid out ETH
mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false);
emit NXMSold(msg.sender, tokenAmount, ethOut);
}
/**
* @dev Get value in tokens for an ethAmount purchase.
* @param ethAmount amount of ETH used for buying.
* @return tokenValue tokens obtained by buying worth of ethAmount
*/
function getNXMForEth(
uint ethAmount
) public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth);
}
function calculateNXMForEth(
uint ethAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Purchases worth higher than 5% of MCReth are not allowed"
);
/*
The price formula is:
P(V) = A + MCReth / C * MCR% ^ 4
where MCR% = V / MCReth
P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4
To compute the number of tokens issued we can integrate with respect to V the following:
ΔT = ΔV / P(V)
which assumes that for an infinitesimally small change in locked value V price is constant and we
get an infinitesimally change in token supply ΔT.
This is not computable on-chain, below we use an approximation that works well assuming
* MCR% stays within [100%, 400%]
* ethAmount <= 5% * MCReth
Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted.
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V.
adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue)
adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1
Evaluating the above using the antiderivative of the function we get:
adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3)
*/
if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) {
/*
If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A.
If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price).
This avoids overflow in the calculateIntegralAtPoint computation.
This approximation is safe from arbitrage since at MCR% < 100% no sells are possible.
*/
uint tokenPrice = CONSTANT_A;
return ethAmount.mul(1e18).div(tokenPrice);
}
// MCReth * C /(3 * V0 ^ 3)
uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth);
// MCReth * C / (3 * V1 ^3)
uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount);
uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth);
uint adjustedTokenAmount = point0.sub(point1);
/*
Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above,
and to that add the A constant (the price offset previously removed in the adjusted Price formula)
to obtain the finalPrice and ultimately the tokenValue based on the finalPrice.
adjustedPrice = ethAmount / adjustedTokenAmount
finalPrice = adjustedPrice + A
tokenValue = ethAmount / finalPrice
*/
// ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount
uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount);
uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A);
return ethAmount.mul(1e18).div(tokenPrice);
}
/**
* @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18
* computation result is multiplied by 1e18 to allow for a precision of 18 decimals.
* NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity
* WARNING: this low-level function should be called from a contract which checks that
* mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0
*/
function calculateIntegralAtPoint(
uint assetValue,
uint mcrEth
) internal pure returns (uint) {
return CONSTANT_C
.mul(1e18)
.div(3)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue);
}
function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) {
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth);
}
/**
* @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%.
* for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%.
* for values higher than that sell spread may exceed 2.5%
* (The higher amount being sold at any given time the higher the spread)
*/
function calculateEthForNXM(
uint nxmAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
// Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price
uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth);
uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18);
// Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1
uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount);
uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth);
// Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ]
// Sell Spread = 2.5%
uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000);
uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1;
uint ethAmount = finalPrice.mul(nxmAmount).div(1e18);
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Sales worth more than 5% of MCReth are not allowed"
);
return ethAmount;
}
function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) {
return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth);
}
/**
* @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4
*/
function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) {
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS);
return mcrEth
.mul(mcrRatio ** TOKEN_EXPONENT)
.div(CONSTANT_C)
.div(precisionDecimals)
.add(CONSTANT_A);
}
/**
* @dev Returns the NXM price in a given asset
* @param asset Asset name.
*/
function getTokenPrice(address asset) public view returns (uint tokenPrice) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth);
return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth);
}
function getMCRRatio() public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateMCRRatio(totalAssetValue, mcrEth);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MIN_ETH") {
minPoolEth = value;
return;
}
revert("Pool: unknown parameter");
}
function updateAddressParameters(bytes8 code, address value) external onlyGovernance {
if (code == "SWP_OP") {
swapOperator = value;
return;
}
if (code == "PRC_FEED") {
priceFeedOracle = PriceFeedOracle(value);
return;
}
revert("Pool: unknown parameter");
}
}
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;
}
}
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);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.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 {
bool private _notEntered;
constructor () internal {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/*
Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
*/
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract MasterAware {
INXMMaster public master;
modifier onlyMember {
require(master.isMember(msg.sender), "Caller is not a member");
_;
}
modifier onlyInternal {
require(master.isInternal(msg.sender), "Caller is not an internal contract");
_;
}
modifier onlyMaster {
if (address(master) != address(0)) {
require(address(master) == msg.sender, "Not master");
}
_;
}
modifier onlyGovernance {
require(
master.checkIsAuthToGoverned(msg.sender),
"Caller is not authorized to govern"
);
_;
}
modifier whenPaused {
require(master.isPause(), "System is not paused");
_;
}
modifier whenNotPaused {
require(!master.isPause(), "System is paused");
_;
}
function changeDependentContractAddress() external;
function changeMasterAddress(address masterAddress) public onlyMaster {
master = INXMMaster(masterAddress);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IPool {
function transferAssetToSwapOperator(address asset, uint amount) external;
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
);
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external;
function minPoolEth() external returns (uint);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../claims/Incidents.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "./QuotationData.sol";
contract Quotation is MasterAware, ReentrancyGuard {
using SafeMath for uint;
ClaimsReward public cr;
Pool public pool;
IPooledStaking public pooledStaking;
QuotationData public qd;
TokenController public tc;
TokenData public td;
Incidents public incidents;
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
cr = ClaimsReward(master.getLatestAddress("CR"));
pool = Pool(master.getLatestAddress("P1"));
pooledStaking = IPooledStaking(master.getLatestAddress("PS"));
qd = QuotationData(master.getLatestAddress("QD"));
tc = TokenController(master.getLatestAddress("TC"));
td = TokenData(master.getLatestAddress("TD"));
incidents = Incidents(master.getLatestAddress("IC"));
}
// solhint-disable-next-line no-empty-blocks
function sendEther() public payable {}
/**
* @dev Expires a cover after a set period of time and changes the status of the cover
* @dev Reduces the total and contract sum assured
* @param coverId Cover Id.
*/
function expireCover(uint coverId) external {
uint expirationDate = qd.getValidityOfCover(coverId);
require(expirationDate < now, "Quotation: cover is not due to expire");
uint coverStatus = qd.getCoverStatusNo(coverId);
require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired");
(/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId);
require(!hasOpenClaim, "Quotation: cover has an open claim");
if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) {
(,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId);
qd.subFromTotalSumAssured(currency, amount);
qd.subFromTotalSumAssuredSC(contractAddress, currency, amount);
}
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired));
}
function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external {
uint gracePeriod = tc.claimSubmissionGracePeriod();
for (uint i = 0; i < coverIds.length; i++) {
uint expirationDate = qd.getValidityOfCover(coverIds[i]);
require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration");
}
tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes);
}
function getWithdrawableCoverNoteCoverIds(
address coverOwner
) public view returns (
uint[] memory expiredCoverIds,
bytes32[] memory lockReasons
) {
uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner);
uint[] memory expiredIdsQueue = new uint[](coverIds.length);
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint expiredQueueLength = 0;
for (uint i = 0; i < coverIds.length; i++) {
uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]);
uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod);
(/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]);
if (!hasOpenClaim && gracePeriodExpirationDate < now) {
expiredIdsQueue[expiredQueueLength] = coverIds[i];
expiredQueueLength++;
}
}
expiredCoverIds = new uint[](expiredQueueLength);
lockReasons = new bytes32[](expiredQueueLength);
for (uint i = 0; i < expiredQueueLength; i++) {
expiredCoverIds[i] = expiredIdsQueue[i];
lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i]));
}
}
function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) {
uint withdrawableAmount;
bytes32[] memory lockReasons;
(/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner);
for (uint i = 0; i < lockReasons.length; i++) {
uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]);
withdrawableAmount = withdrawableAmount.add(coverNoteAmount);
}
return withdrawableAmount;
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] calldata coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyMember whenNotPaused {
tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyInternal {
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s,
false
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySignature(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
require(contractAddress != address(0));
bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
coverDetails[0],
currency,
coverPeriod,
contractAddress,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover(//solhint-disable-line
address payable from,
address contractAddress,
bytes4 coverCurrency,
uint[] memory coverDetails,
uint16 coverPeriod
) internal {
address underlyingToken = incidents.underlyingToken(contractAddress);
if (underlyingToken != address(0)) {
address coverAsset = cr.getCurrencyAssetAddress(coverCurrency);
require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product");
}
uint cid = qd.getCoverLength();
qd.addCover(
coverPeriod,
coverDetails[0],
from,
coverCurrency,
contractAddress,
coverDetails[1],
coverDetails[2]
);
uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100);
if (underlyingToken == address(0)) {
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod);
bytes32 reason = keccak256(abi.encodePacked("CN", from, cid));
// mint and lock cover note
td.setDepositCNAmount(cid, coverNoteAmount);
tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod);
} else {
// minted directly to member's wallet
tc.mint(from, coverNoteAmount);
}
qd.addInTotalSumAssured(coverCurrency, coverDetails[0]);
qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]);
uint coverPremiumInNXM = coverDetails[2];
uint stakersRewardPercentage = td.stakerCommissionPer();
uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100);
pooledStaking.accumulateReward(contractAddress, rewardValue);
}
/**
* @dev Makes a cover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool isNXM
) internal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
address asset = cr.getCurrencyAssetAddress(coverCurr);
if (coverCurr != "ETH" && !isNXM) {
pool.transferAssetFrom(asset, from, coverDetails[1]);
}
require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
function createCover(
address payable from,
address scAddress,
bytes4 currency,
uint[] calldata coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyInternal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, currency, coverDetails, coverPeriod);
}
// referenced in master, keeping for now
// solhint-disable-next-line no-empty-blocks
function transferAssetsToNewContract(address) external pure {}
function freeUpHeldCovers() external nonReentrant {
IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI"));
uint membershipFee = td.joiningFee();
uint lastCoverId = 106;
for (uint id = 1; id <= lastCoverId; id++) {
if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) {
continue;
}
(/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id);
(/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id);
uint refundedETH = membershipFee;
uint coverPremium = coverDetails[1];
if (qd.refundEligible(userAddress)) {
qd.setRefundEligible(userAddress, false);
}
qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
if (currency == "ETH") {
refundedETH = refundedETH.add(coverPremium);
} else {
require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed");
}
userAddress.transfer(refundedETH);
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface Aggregator {
function latestAnswer() external view returns (int);
}
contract PriceFeedOracle {
using SafeMath for uint;
mapping(address => address) public aggregators;
address public daiAddress;
address public stETH;
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor (
address _daiAggregator,
address _daiAddress,
address _stEthAddress
) public {
aggregators[_daiAddress] = _daiAggregator;
daiAddress = _daiAddress;
stETH = _stEthAddress;
}
/**
* @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset
* @param asset quoted currency
* @return price in ether
*/
function getAssetToEthRate(address asset) public view returns (uint) {
if (asset == ETH || asset == stETH) {
return 1 ether;
}
address aggregatorAddress = aggregators[asset];
if (aggregatorAddress == address(0)) {
revert("PriceFeedOracle: Oracle asset not found");
}
int rate = Aggregator(aggregatorAddress).latestAnswer();
require(rate > 0, "PriceFeedOracle: Rate must be > 0");
return uint(rate);
}
/**
* @dev Returns the amount of currency that is equivalent to ethIn amount of ether.
* @param asset quoted Supported values: ["DAI", "ETH"]
* @param ethIn amount of ether to be converted to the currency
* @return price in ether
*/
function getAssetForEth(address asset, uint ethIn) external view returns (uint) {
if (asset == daiAddress) {
return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress));
}
if (asset == ETH || asset == stETH) {
return ethIn;
}
revert("PriceFeedOracle: Unknown asset");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "./external/OZIERC20.sol";
import "./external/OZSafeMath.sol";
contract NXMToken is OZIERC20 {
using OZSafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
mapping(address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, amount);
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, 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
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @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) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, 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
)
internal
{
_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);
}
/**
* @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 amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
import "../../interfaces/IPooledStaking.sol";
import "../claims/ClaimsData.sol";
import "./NXMToken.sol";
import "./external/LockHandler.sol";
contract TokenController is LockHandler, Iupgradable {
using SafeMath for uint256;
struct CoverInfo {
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// note: still 224 bits available here, can be used later
}
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime;
uint public claimSubmissionGracePeriod;
// coverId => CoverInfo
mapping(uint => CoverInfo) public coverInfo;
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount);
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
modifier onlyGovernance {
require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance");
_;
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
function markCoverClaimOpen(uint coverId) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// reads all of them using a single SLOAD
(claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim);
// no safemath for uint16 but should be safe from
// overflows as there're max 2 claims per cover
claimCount = claimCount + 1;
require(claimCount <= 2, "TokenController: Max claim count exceeded");
require(hasOpenClaim == false, "TokenController: Cover already has an open claim");
require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims");
// should use a single SSTORE for both
(info.claimCount, info.hasOpenClaim) = (claimCount, true);
}
/**
* @param coverId cover id (careful, not claim id!)
* @param isAccepted claim verdict
*/
function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open");
// should use a single SSTORE for both
(info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted);
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) {
require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address");
token.operatorTransfer(_from, _value);
token.transfer(_to, _value);
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause {
require(minCALockTime <= _time, "TokenController: Must lock for minimum time");
require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
// If tokens are already locked, then functions extendLock or
// increaseClaimAssessmentLock should be used to make any changes
_lock(msg.sender, "CLA", _amount, _time);
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Mints and locks a specified amount of tokens against an address,
* for a CN reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function mintCoverNote(
address _of,
bytes32 _reason,
uint256 _amount,
uint256 _time
) external onlyInternal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.mint(address(this), _amount);
uint256 lockedUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, lockedUntil, false);
emit Locked(_of, _reason, _amount, lockedUntil);
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _time Lock extension time in seconds
*/
function extendClaimAssessmentLock(uint256 _time) external checkPause {
uint256 validity = getLockedTokensValidity(msg.sender, "CLA");
require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
_extendLock(msg.sender, "CLA", _time);
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _amount Number of tokens to be increased
*/
function increaseClaimAssessmentLock(uint256 _amount) external checkPause
{
require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked");
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount);
emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity);
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom(address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the withdrawable tokens against CLA of a specified address
* @param _of Address of user, claiming back withdrawable tokens against CLA
*/
function withdrawClaimAssessmentTokens(address _of) external checkPause {
uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA");
if (withdrawableTokens > 0) {
locked[_of]["CLA"].claimed = true;
emit Unlocked(_of, "CLA", withdrawableTokens);
token.transfer(_of, withdrawableTokens);
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param value value to set
*/
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MNCLT") {
minCALockTime = value;
return;
}
if (code == "GRACEPER") {
claimSubmissionGracePeriod = value;
return;
}
revert("TokenController: invalid param code");
}
function getLockReasons(address _of) external view returns (bytes32[] memory reasons) {
return lockReason[_of];
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) {
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns tokens locked and validity for a specified address and reason
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLockedWithValidity(address _of, bytes32 _reason)
public
view
returns (uint256 amount, uint256 validity)
{
bool claimed = locked[_of][_reason].claimed;
amount = locked[_of][_reason].amount;
validity = locked[_of][_reason].validity;
if (claimed) {
amount = 0;
}
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total amount of locked and staked tokens.
* Used by MemberRoles to check eligibility for withdraw / switch membership.
* Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes
* Does not take into account pending burns.
* @param _of member whose locked tokens are to be calculate
*/
function totalLockedBalance(address _of) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.operatorTransfer(_of, _amount);
uint256 validUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.transfer(_of, _amount);
emit Unlocked(_of, _reason, _amount);
}
function withdrawCoverNote(
address _of,
uint[] calldata _coverIds,
uint[] calldata _indexes
) external onlyInternal {
uint reasonCount = lockReason[_of].length;
uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found");
uint totalAmount = 0;
// The iteration is done from the last to first to prevent reason indexes from
// changing due to the way we delete the items (copy last to current and pop last).
// The provided indexes array must be ordered, otherwise reason index checks will fail.
for (uint i = _coverIds.length; i > 0; i--) {
bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim;
require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim");
// note: cover owner is implicitly checked using the reason hash
bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1]));
uint _reasonIndex = _indexes[i - 1];
require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index");
uint amount = locked[_of][_reason].amount;
totalAmount = totalAmount.add(amount);
delete locked[_of][_reason];
if (lastReasonIndex != _reasonIndex) {
lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
emit Unlocked(_of, _reason, amount);
if (lastReasonIndex > 0) {
lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch");
}
}
token.transfer(_of, totalAmount);
}
function removeEmptyReason(address _of, bytes32 _reason, uint _index) external {
_removeEmptyReason(_of, _reason, _index);
}
function removeMultipleEmptyReasons(
address[] calldata _members,
bytes32[] calldata _reasons,
uint[] calldata _indexes
) external {
require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ");
require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ");
for (uint i = _members.length; i > 0; i--) {
uint idx = i - 1;
_removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]);
}
}
function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal {
uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty");
require(lockReason[_of][_index] == _reason, "TokenController: bad reason index");
require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero");
if (lastReasonIndex != _index) {
lockReason[_of][_index] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
}
function initialize() external {
require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized");
claimSubmissionGracePeriod = 120 days;
migrate();
}
function migrate() internal {
ClaimsData cd = ClaimsData(ms.getLatestAddress("CD"));
uint totalClaims = cd.actualClaimLength() - 1;
// fix stuck claims 21 & 22
cd.changeFinalVerdict(20, -1);
cd.setClaimStatus(20, 6);
cd.changeFinalVerdict(21, -1);
cd.setClaimStatus(21, 6);
// reduce claim assessment lock period for members locked for more than 180 days
// extracted using scripts/extract-ca-locked-more-than-180.js
address payable[3] memory members = [
0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc,
0x6b5DCDA27b5c3d88e71867D6b10b35372208361F,
0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617
];
for (uint i = 0; i < members.length; i++) {
if (locked[members[i]]["CLA"].validity > now + 180 days) {
locked[members[i]]["CLA"].validity = now + 180 days;
}
}
for (uint i = 1; i <= totalClaims; i++) {
(/*id*/, uint status) = cd.getClaimStatusNumber(i);
(/*id*/, uint coverId) = cd.getClaimCoverId(i);
int8 verdict = cd.getFinalVerdict(i);
// SLOAD
CoverInfo memory info = coverInfo[coverId];
info.claimCount = info.claimCount + 1;
info.hasAcceptedClaim = (status == 14);
info.hasOpenClaim = (verdict == 0);
// SSTORE
coverInfo[coverId] = info;
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenData.sol";
import "./LegacyMCR.sol";
contract MCR is MasterAware {
using SafeMath for uint;
Pool public pool;
QuotationData public qd;
// sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot)
uint96 _unused;
// the following values are expressed in basis points
uint24 public mcrFloorIncrementThreshold = 13000;
uint24 public maxMCRFloorIncrement = 100;
uint24 public maxMCRIncrement = 500;
uint24 public gearingFactor = 48000;
// min update between MCR updates in seconds
uint24 public minUpdateTime = 3600;
uint112 public mcrFloor;
uint112 public mcr;
uint112 public desiredMCR;
uint32 public lastUpdateTime;
LegacyMCR public previousMCR;
event MCRUpdated(
uint mcr,
uint desiredMCR,
uint mcrFloor,
uint mcrETHWithGear,
uint totalSumAssured
);
uint constant UINT24_MAX = ~uint24(0);
uint constant MAX_MCR_ADJUSTMENT = 100;
uint constant BASIS_PRECISION = 10000;
constructor (address masterAddress) public {
changeMasterAddress(masterAddress);
if (masterAddress != address(0)) {
previousMCR = LegacyMCR(master.getLatestAddress("MC"));
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
qd = QuotationData(master.getLatestAddress("QD"));
pool = Pool(master.getLatestAddress("P1"));
initialize();
}
function initialize() internal {
address currentMCR = master.getLatestAddress("MC");
if (address(previousMCR) == address(0) || currentMCR != address(this)) {
// already initialized or not ready for initialization
return;
}
// fetch MCR parameters from previous contract
uint112 minCap = 7000 * 1e18;
mcrFloor = uint112(previousMCR.variableMincap()) + minCap;
mcr = uint112(previousMCR.getLastMCREther());
desiredMCR = mcr;
mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100());
maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100());
// set last updated time to now
lastUpdateTime = uint32(block.timestamp);
previousMCR = LegacyMCR(address(0));
}
/**
* @dev Gets total sum assured (in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns (uint) {
PriceFeedOracle priceFeed = pool.priceFeedOracle();
address daiAddress = priceFeed.daiAddress();
uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18);
uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18);
uint daiRate = priceFeed.getAssetToEthRate(daiAddress);
uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18);
return ethAmount.add(daiAmountInEth);
}
/*
* @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated
* and a new desiredMCR value to move towards is set.
*
*/
function updateMCR() public {
_updateMCR(pool.getPoolValueInEth(), false);
}
function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal {
_updateMCR(poolValueInEth, forceUpdate);
}
function _updateMCR(uint poolValueInEth, bool forceUpdate) internal {
// read with 1 SLOAD
uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold;
uint _maxMCRFloorIncrement = maxMCRFloorIncrement;
uint _gearingFactor = gearingFactor;
uint _minUpdateTime = minUpdateTime;
uint _mcrFloor = mcrFloor;
// read with 1 SLOAD
uint112 _mcr = mcr;
uint112 _desiredMCR = desiredMCR;
uint32 _lastUpdateTime = lastUpdateTime;
if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) {
return;
}
if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) {
// MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3
// MCR floor is monotonically increasing.
uint basisPointsAdjustment = min(
_maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days),
_maxMCRFloorIncrement
);
uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION);
require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow');
mcrFloor = uint112(newMCRFloor);
}
// sync the current virtual MCR value to storage
uint112 newMCR = uint112(getMCR());
if (newMCR != _mcr) {
mcr = newMCR;
}
// the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based
// on the changes in the totalSumAssured in the system.
uint totalSumAssured = getAllSumAssurance();
uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor);
uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor));
if (newDesiredMCR != _desiredMCR) {
desiredMCR = newDesiredMCR;
}
lastUpdateTime = uint32(block.timestamp);
emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured);
}
/**
* @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away
* from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime.
* The total change in virtual MCR cannot exceed 1% of stored mcr.
*
* This approach allows for the MCR to change smoothly across time without sudden jumps between values, while
* always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR
* so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa.
*
* @return mcr
*/
function getMCR() public view returns (uint) {
// read with 1 SLOAD
uint _mcr = mcr;
uint _desiredMCR = desiredMCR;
uint _lastUpdateTime = lastUpdateTime;
if (block.timestamp == _lastUpdateTime) {
return _mcr;
}
uint _maxMCRIncrement = maxMCRIncrement;
uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days);
basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT);
if (_desiredMCR > _mcr) {
return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR);
}
// in case desiredMCR <= mcr
return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR);
}
function getGearedMCR() external view returns (uint) {
return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor);
}
function min(uint x, uint y) pure internal returns (uint) {
return x < y ? x : y;
}
function max(uint x, uint y) pure internal returns (uint) {
return x > y ? x : y;
}
/**
* @dev Updates Uint Parameters
* @param code parameter code
* @param val new value
*/
function updateUintParameters(bytes8 code, uint val) public {
require(master.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
require(val <= UINT24_MAX, "MCR: value too large");
mcrFloorIncrementThreshold = uint24(val);
} else if (code == "DMCI") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRFloorIncrement = uint24(val);
} else if (code == "MMIC") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRIncrement = uint24(val);
} else if (code == "GEAR") {
require(val <= UINT24_MAX, "MCR: value too large");
gearingFactor = uint24(val);
} else if (code == "MUTI") {
require(val <= UINT24_MAX, "MCR: value too large");
minUpdateTime = uint24(val);
} else {
revert("Invalid param code");
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns (bool);
function isInternal(address _add) public view returns (bool);
function isPause() public view returns (bool check);
function isOwner(address _add) public view returns (bool);
function isMember(address _add) public view returns (bool);
function checkIsAuthToGoverned(address _add) public view returns (bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns (address _add);
function dAppToken() public view returns (address _add);
function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress);
}
/* Copyright (C) 2020 NexusMutual.io
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/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity ^0.5.0;
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../governance/Governance.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Claims.sol";
import "./ClaimsData.sol";
import "../capital/MCR.sol";
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool internal pool;
Governance internal gv;
IPooledStaking internal pooledStaking;
MemberRoles internal memberRoles;
MCR public mcr;
// assigned in constructor
address public DAI;
// constants
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint private constant DECIMAL1E18 = uint(10) ** 18;
constructor (address masterAddress, address _daiAddress) public {
changeMasterAddress(masterAddress);
DAI = _daiAddress;
}
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
memberRoles = MemberRoles(ms.getLatestAddress("MR"));
pool = Pool(ms.getLatestAddress("P1"));
mcr = MCR(ms.getLatestAddress("MC"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
(, uint coverid) = cd.getClaimCoverId(claimid);
(, uint status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) {// when current status is "Claim Accepted Payout Pending"
bool payoutSucceeded = attemptClaimPayout(coverid);
if (payoutSucceeded) {
c1.setClaimStatus(claimid, 14);
} else {
c1.setClaimStatus(claimid, 12);
}
}
}
function getCurrencyAssetAddress(bytes4 currency) public view returns (address) {
if (currency == "ETH") {
return ETH;
}
if (currency == "DAI") {
return DAI;
}
revert("ClaimsReward: unknown asset");
}
function attemptClaimPayout(uint coverId) internal returns (bool success) {
uint sumAssured = qd.getCoverSumAssured(coverId);
// TODO: when adding new cover currencies, fetch the correct decimals for this multiplication
uint sumAssuredWei = sumAssured.mul(1e18);
// get asset address
bytes4 coverCurrency = qd.getCurrencyOfCover(coverId);
address asset = getCurrencyAssetAddress(coverCurrency);
// get payout address
address payable coverHolder = qd.getCoverMemberAddress(coverId);
address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder);
// execute the payout
bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei);
if (payoutSucceeded) {
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = pool.getTokenPrice(asset);
// note: for new assets "18" needs to be replaced with target asset decimals
uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
// adjust total sum assured
(, address coverContract) = qd.getscAddressOfCover(coverId);
qd.subFromTotalSumAssured(coverCurrency, sumAssured);
qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured);
// update MCR since total sum assured and MCR% change
mcr.updateMCRInternal(pool.getPoolValueInEth(), true);
return true;
}
return false;
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenCA(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenMV(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns (uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
}
(reward,,,) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns (uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
// denied
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
tc.markCoverClaimClosed(coverid, false);
_burnCoverNoteDeposit(coverid);
// accepted
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
tc.markCoverClaimClosed(coverid, true);
_unlockCoverNote(coverid);
bool payoutSucceeded = attemptClaimPayout(coverid);
// 12 = payout pending, 14 = payout succeeded
uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
}
}
function _burnCoverNoteDeposit(uint coverId) internal {
address _of = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
uint lockedAmount = tc.tokensLocked(_of, reason);
(uint amount,) = td.depositedCN(coverId);
amount = amount.div(2);
// limit burn amount to actual amount locked
uint burnAmount = lockedAmount < amount ? lockedAmount : amount;
if (burnAmount != 0) {
tc.burnLockedTokens(_of, reason, amount);
}
}
function _unlockCoverNote(uint coverId) internal {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
uint lockedCN = tc.tokensLocked(coverHolder, reason);
if (lockedCN != 0) {
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, - 1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, - 1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex,) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc,,) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total = 0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); // solhint-disable-line
}
}
/* Copyright (C) 2021 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsData.sol";
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../governance/MemberRoles.sol";
import "../token/TokenController.sol";
import "../capital/MCR.sol";
contract Incidents is MasterAware {
using SafeERC20 for IERC20;
using SafeMath for uint;
struct Incident {
address productId;
uint32 date;
uint priceBefore;
}
// contract identifiers
enum ID {CD, CR, QD, TC, MR, P1, PS, MC}
mapping(uint => address payable) public internalContracts;
Incident[] public incidents;
// product id => underlying token (ex. yDAI -> DAI)
mapping(address => address) public underlyingToken;
// product id => covered token (ex. 0xc7ed.....1 -> yDAI)
mapping(address => address) public coveredToken;
// claim id => payout amount
mapping(uint => uint) public claimPayout;
// product id => accumulated burn amount
mapping(address => uint) public accumulatedBurn;
// burn ratio in bps, ex 2000 for 20%
uint public BURN_RATIO;
// burn ratio in bps
uint public DEDUCTIBLE_RATIO;
uint constant BASIS_PRECISION = 10000;
event ProductAdded(
address indexed productId,
address indexed coveredToken,
address indexed underlyingToken
);
event IncidentAdded(
address indexed productId,
uint incidentDate,
uint priceBefore
);
modifier onlyAdvisoryBoard {
uint abRole = uint(MemberRoles.Role.AdvisoryBoard);
require(
memberRoles().checkRole(msg.sender, abRole),
"Incidents: Caller is not an advisory board member"
);
_;
}
function initialize() external {
require(BURN_RATIO == 0, "Already initialized");
BURN_RATIO = 2000;
DEDUCTIBLE_RATIO = 9000;
}
function addProducts(
address[] calldata _productIds,
address[] calldata _coveredTokens,
address[] calldata _underlyingTokens
) external onlyAdvisoryBoard {
require(
_productIds.length == _coveredTokens.length,
"Incidents: Protocols and covered tokens lengths differ"
);
require(
_productIds.length == _underlyingTokens.length,
"Incidents: Protocols and underyling tokens lengths differ"
);
for (uint i = 0; i < _productIds.length; i++) {
address id = _productIds[i];
require(coveredToken[id] == address(0), "Incidents: covered token is already set");
require(underlyingToken[id] == address(0), "Incidents: underlying token is already set");
coveredToken[id] = _coveredTokens[i];
underlyingToken[id] = _underlyingTokens[i];
emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]);
}
}
function incidentCount() external view returns (uint) {
return incidents.length;
}
function addIncident(
address productId,
uint incidentDate,
uint priceBefore
) external onlyGovernance {
address underlying = underlyingToken[productId];
require(underlying != address(0), "Incidents: Unsupported product");
Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore);
incidents.push(incident);
emit IncidentAdded(productId, incidentDate, priceBefore);
}
function redeemPayoutForMember(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address member
) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member);
}
function redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount
) external returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender);
}
function _redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address coverOwner
) internal returns (uint claimId, uint payoutAmount, address coverAsset) {
QuotationData qd = quotationData();
Incident memory incident = incidents[incidentId];
uint sumAssured;
bytes4 currency;
{
address productId;
address _coverOwner;
(/* id */, _coverOwner, productId,
currency, sumAssured, /* premiumNXM */
) = qd.getCoverDetailsByCoverID1(coverId);
// check ownership and covered protocol
require(coverOwner == _coverOwner, "Incidents: Not cover owner");
require(productId == incident.productId, "Incidents: Bad incident id");
}
{
uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days);
uint coverExpirationDate = qd.getValidityOfCover(coverId);
uint coverStartDate = coverExpirationDate.sub(coverPeriod);
// check cover validity
require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident");
require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident");
// check grace period
uint gracePeriod = tokenController().claimSubmissionGracePeriod();
require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired");
}
{
// assumes 18 decimals (eth & dai)
uint decimalPrecision = 1e18;
uint maxAmount;
// sumAssured is currently stored without decimals
uint coverAmount = sumAssured.mul(decimalPrecision);
{
// max amount check
uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION);
maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore);
require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured");
}
// payoutAmount = coveredTokenAmount / maxAmount * coverAmount
// = coveredTokenAmount * coverAmount / maxAmount
payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount);
}
{
TokenController tc = tokenController();
// mark cover as having a successful claim
tc.markCoverClaimOpen(coverId);
tc.markCoverClaimClosed(coverId, true);
// create the claim
ClaimsData cd = claimsData();
claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
cd.setClaimStatus(claimId, 14);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted));
claimPayout[claimId] = payoutAmount;
}
coverAsset = claimsReward().getCurrencyAssetAddress(currency);
_sendPayoutAndPushBurn(
incident.productId,
address(uint160(coverOwner)),
coveredTokenAmount,
coverAsset,
payoutAmount
);
qd.subFromTotalSumAssured(currency, sumAssured);
qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured);
mcr().updateMCRInternal(pool().getPoolValueInEth(), true);
}
function pushBurns(address productId, uint maxIterations) external {
uint burnAmount = accumulatedBurn[productId];
delete accumulatedBurn[productId];
require(burnAmount > 0, "Incidents: No burns to push");
require(maxIterations >= 30, "Incidents: Pass at least 30 iterations");
IPooledStaking ps = pooledStaking();
ps.pushBurn(productId, burnAmount);
ps.processPendingActions(maxIterations);
}
function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance {
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferAmount);
}
function _sendPayoutAndPushBurn(
address productId,
address payable coverOwner,
uint coveredTokenAmount,
address coverAsset,
uint payoutAmount
) internal {
address _coveredToken = coveredToken[productId];
// pull depegged tokens
IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount);
Pool p1 = pool();
// send the payoutAmount
{
address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner);
bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount);
require(success, "Incidents: Payout failed");
}
{
// burn
uint decimalPrecision = 1e18;
uint assetPerNxm = p1.getTokenPrice(coverAsset);
uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm);
uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION);
accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount);
}
}
function claimsData() internal view returns (ClaimsData) {
return ClaimsData(internalContracts[uint(ID.CD)]);
}
function claimsReward() internal view returns (ClaimsReward) {
return ClaimsReward(internalContracts[uint(ID.CR)]);
}
function quotationData() internal view returns (QuotationData) {
return QuotationData(internalContracts[uint(ID.QD)]);
}
function tokenController() internal view returns (TokenController) {
return TokenController(internalContracts[uint(ID.TC)]);
}
function memberRoles() internal view returns (MemberRoles) {
return MemberRoles(internalContracts[uint(ID.MR)]);
}
function pool() internal view returns (Pool) {
return Pool(internalContracts[uint(ID.P1)]);
}
function pooledStaking() internal view returns (IPooledStaking) {
return IPooledStaking(internalContracts[uint(ID.PS)]);
}
function mcr() internal view returns (MCR) {
return MCR(internalContracts[uint(ID.MC)]);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "BURNRATE") {
require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000");
BURN_RATIO = value;
return;
}
if (code == "DEDUCTIB") {
require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000");
DEDUCTIBLE_RATIO = value;
return;
}
revert("Incidents: Invalid parameter");
}
function changeDependentContractAddress() external {
INXMMaster master = INXMMaster(master);
internalContracts[uint(ID.CD)] = master.getLatestAddress("CD");
internalContracts[uint(ID.CR)] = master.getLatestAddress("CR");
internalContracts[uint(ID.QD)] = master.getLatestAddress("QD");
internalContracts[uint(ID.TC)] = master.getLatestAddress("TC");
internalContracts[uint(ID.MR)] = master.getLatestAddress("MR");
internalContracts[uint(ID.P1)] = master.getLatestAddress("P1");
internalContracts[uint(ID.PS)] = master.getLatestAddress("PS");
internalContracts[uint(ID.MC)] = master.getLatestAddress("MC");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {//solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount);
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount);
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount);
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount);
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount);
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns (uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns (bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover}
enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested}
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount);
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount);
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns (uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns (address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns (uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns (uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns (uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns (uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns (uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns (address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface OZIERC20 {
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
);
}
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library OZSafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
pragma solidity ^0.5.0;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function processPendingActions(uint maxIterations) external returns (bool finished);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt);
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns (
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns (
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns (uint voteCount) {
return allvotes.length.sub(1); // Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns (uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns (uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns (
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns (address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns (uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns (uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns (uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns (uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns (
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns (
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns (
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns (
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns (
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns (uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns (uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns (uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns (uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns (int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns (uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns (uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns (
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); // 0 Pending-Claim Assessor Vote
_pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); // 12 Claim Accepted Payout Pending
_pushStatus(0, 0); // 13 Claim Accepted No Payout
_pushStatus(0, 0); // 14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract LockHandler {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
}
pragma solidity ^0.5.0;
interface LegacyMCR {
function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external;
function addLastMCRData(uint64 date) external;
function changeDependentContractAddress() external;
function getAllSumAssurance() external view returns (uint amount);
function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice);
function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice);
function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp);
function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold);
function getMaxSellTokens() external view returns (uint maxTokens);
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val);
function updateUintParameters(bytes8 code, uint val) external;
function variableMincap() external view returns (uint);
function dynamicMincapThresholdx100() external view returns (uint);
function dynamicMincapIncrementx100() external view returns (uint);
function getLastMCREther() external view returns (uint);
}
// /* Copyright (C) 2017 GovBlocks.io
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../token/TokenController.sol";
import "./MemberRoles.sol";
import "./ProposalCategory.sol";
import "./external/IGovernance.sol";
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint => uint) memberVoteValue;
mapping(uint => uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping(address => mapping(uint => uint)) public memberProposalVote;
mapping(address => uint) public followerDelegation;
mapping(address => uint) internal followerCount;
mapping(address => uint[]) internal leaderDelegation;
mapping(uint => VoteTally) public proposalVoteTally;
mapping(address => bool) public isOpenForDelegation;
mapping(address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns (uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return (
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) {
return (
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns (uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns (uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns (uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns (bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(,,,, mrAllowed,,) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns (bool delegated) {
for (uint i = 0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns (uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns (uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime,) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10 ** 18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10 ** 18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns (uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns (bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
// solhint-disable-next-line avoid-low-level-calls
(bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(,, _majorityVote,,,,) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/MasterAware.sol";
import "../cover/QuotationData.sol";
import "./NXMToken.sol";
import "./TokenController.sol";
import "./TokenData.sol";
contract TokenFunctions is MasterAware {
using SafeMath for uint;
TokenController public tc;
NXMToken public tk;
QuotationData public qd;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns (uint) {
uint[] memory coverIds = qd.getAllCoversOfUser(_of);
uint total;
for (uint i = 0; i < coverIds.length; i++) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i]));
uint coverNote = tc.tokensLocked(_of, reason);
total = total.add(coverNote);
}
return total;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tc = TokenController(master.getLatestAddress("TC"));
tk = NXMToken(master.tokenAddress());
qd = QuotationData(master.getLatestAddress("QD"));
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance {
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns (bool) {
return now < tk.isLockedForMV(_of);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "../token/TokenFunctions.sol";
import "./ClaimsData.sol";
import "./Incidents.sol";
contract Claims is Iupgradable {
using SafeMath for uint;
TokenController internal tc;
ClaimsReward internal cr;
Pool internal p1;
ClaimsData internal cd;
TokenData internal td;
QuotationData internal qd;
Incidents internal incidents;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns (uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool(ms.getLatestAddress("P1"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
incidents = Incidents(ms.getLatestAddress("IC"));
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) external {
_submitClaim(coverId, msg.sender);
}
function submitClaimForMember(uint coverId, address member) external onlyInternal {
_submitClaim(coverId, member);
}
function _submitClaim(uint coverId, address member) internal {
require(!ms.isPause(), "Claims: System is paused");
(/* id */, address contractAddress) = qd.getscAddressOfCover(coverId);
address token = incidents.coveredToken(contractAddress);
require(token == address(0), "Claims: Product type does not allow claims");
address coverOwner = qd.getCoverMemberAddress(coverId);
require(coverOwner == member, "Claims: Not cover owner");
uint expirationDate = qd.getValidityOfCover(coverId);
uint gracePeriod = tc.claimSubmissionGracePeriod();
require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired");
tc.markCoverClaimOpen(coverId);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
uint claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
}
// solhint-disable-next-line no-empty-blocks
function submitClaimAfterEPOff() external pure {}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
// solhint-disable-next-line no-empty-blocks
function pauseAllPendingClaimsVoting() external pure {}
// solhint-disable-next-line no-empty-blocks
function startAllPendingClaimsVoting() external pure {}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns (int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = - 1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
cd.setClaimdateUpd(claimId, now);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Governance.sol";
import "./external/Governed.sol";
contract MemberRoles is Governed, Iupgradable {
TokenController public tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
mapping (address => address payable) internal claimPayoutAddress;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember(
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner(
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0)) {
require(masterAddress == msg.sender);
}
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate(address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(//solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(//solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i = 0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
tc.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
tc.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); // solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); // solhint-disable-line
}
}
/**
* @dev withdraws membership for msg.sender if currently a member.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(msg.sender);
tc.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
tc.removeFromWhitelist(msg.sender); // need clarification on whitelist
if (claimPayoutAddress[msg.sender] != address(0)) {
claimPayoutAddress[msg.sender] = address(0);
emit ClaimPayoutAddressSet(msg.sender, address(0));
}
}
/**
* @dev switches membership for msg.sender to the specified address.
* @param newAddress address of user to forward membership.
*/
function switchMembership(address newAddress) external {
_switchMembership(msg.sender, newAddress);
tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender));
}
function switchMembershipOf(address member, address newAddress) external onlyInternal {
_switchMembership(member, newAddress);
}
/**
* @dev switches membership for member to the specified address.
* @param newAddress address of user to forward membership.
*/
function _switchMembership(address member, address newAddress) internal {
require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress));
require(tc.totalLockedBalance(member) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(member);
tc.addToWhitelist(newAddress);
_updateRole(newAddress, uint(Role.Member), true);
_updateRole(member, uint(Role.Member), false);
tc.removeFromWhitelist(member);
address payable previousPayoutAddress = claimPayoutAddress[member];
if (previousPayoutAddress != address(0)) {
address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress;
claimPayoutAddress[member] = address(0);
claimPayoutAddress[newAddress] = storedAddress;
// emit event for old address reset
emit ClaimPayoutAddressSet(member, address(0));
if (storedAddress != address(0)) {
// emit event for setting the payout address on the new member address if it's non zero
emit ClaimPayoutAddressSet(newAddress, storedAddress);
}
}
emit switchedMembership(member, newAddress, now);
}
function getClaimPayoutAddress(address payable _member) external view returns (address payable) {
address payable payoutAddress = claimPayoutAddress[_member];
return payoutAddress != address(0) ? payoutAddress : _member;
}
function setClaimPayoutAddress(address payable _address) external {
require(!ms.isPause(), "system is paused");
require(ms.isMember(msg.sender), "sender is not a member");
require(_address != msg.sender, "should be different than the member address");
claimPayoutAddress[msg.sender] = _address;
emit ClaimPayoutAddressSet(msg.sender, _address);
}
/// @dev Return number of member roles
function totalRoles() public view returns (uint256) {//solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns (bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../../abstract/Iupgradable.sol";
import "./MemberRoles.sol";
import "./external/Governed.sol";
import "./external/IProposalCategory.sol";
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping(uint => CategoryAction) internal categoryActionData;
mapping(uint => uint) public categoryABReq;
mapping(uint => uint) public isSpecialResolution;
mapping(uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
) external {}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external {}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns (uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) {
return (
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) {
return (
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
) public {}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns (uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns (uint closeValue);
function allowedToCatgorize() public view returns (uint roleId);
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
interface IMaster {
function getLatestAddress(bytes2 _module) external view returns (address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns (bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns (
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns (
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns (uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
| * @dev Get number of Claims queued for submission during emergency pause./ | function getLengthOfClaimSubmittedAtEP() external view returns (uint len) {
len = claimPause.length;
}
| 2,578,322 | [
1,
967,
1300,
434,
28895,
12234,
364,
8515,
4982,
801,
24530,
11722,
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
] | [
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,
225,
445,
9888,
951,
9762,
28882,
861,
10541,
1435,
3903,
1476,
1135,
261,
11890,
562,
13,
288,
203,
565,
562,
273,
7516,
19205,
18,
2469,
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
] |
pragma solidity >=0.4.22 <0.7.0;
contract PowerBid {
enum Phase {
AUCTION,
CONSUMPTION,
FINISHED,
GAIN_WITHDRAWN,
PRICE_WITHDRAWN,
COMPLETED,
VIOLATED,
VIOLATION_RESOLVED}
// Parameters of the auction. Times are either
// absolute unix timestamps (seconds since 1970-01-01)
// or time periods in seconds.
address payable public consumer;
uint public auctionStartTime;
uint public consumptionStartTime; // t0
uint public consumptionEndTime; // t1
uint public requiredNRG; // in watts hour
uint public maxPrice; // max flat rate price for watts * hours (t1-t0) in the given period
// Current state of the auction.
address payable public bestSupplier;
uint public bestPrice;
Phase public state;
uint public auctionEndTime;
uint public consumptionTime;
// Events that will be emitted on changes.
event BestPriceUpdated(address bidder, uint amount);
event AuctionEnded(address winner, uint amount);
event Consumed(address consumer, address supplier, uint amount,uint price);
/// Create a power bidding auction with `_consumptionStartTime`
/// that represents the start time of the future consumption with `_consumptionEndTimeseconds`
/// as the end time. `_requiredEnergy` is the amount of energy required between `_consumptionEndTimeseconds` - `_consumptionStartTime`
/// on a flat rate
constructor(
uint auctionPeriodSeconds,
uint consumptionPeriodSeconds,
uint requiredEnergy
) public payable {
require(requiredEnergy > 0, "required energy must be greater than 0 wh");
require(msg.value > 0 ,"max price must be greater than 0");
require(auctionPeriodSeconds > 0, "auction period must be greater than 0");
require(consumptionPeriodSeconds > 0, "consumption period must be greater than 0");
consumer = msg.sender;
maxPrice = msg.value;
requiredNRG = requiredEnergy;
auctionStartTime = now;
consumptionStartTime = now + auctionPeriodSeconds;
consumptionEndTime = consumptionStartTime + consumptionPeriodSeconds;
state = Phase.AUCTION;
auctionEndTime = consumptionTime = 0;
}
/// Bid on the auction
function bid(uint _price) public {
// No arguments are necessary, all
// information is already part of
// the transaction. Function is not reciving Ether
// as the consumer pays
// Revert the call if the bidding
// period is over.
require(state == Phase.AUCTION, "Auction already ended.");
// Don't allow self bids
require(msg.sender != consumer);
// no free power
require(_price > 0);
// If the price is not better, send the
// money back.
require(
_price < bestPrice || (bestSupplier == address(0) && _price <= maxPrice),
"There already is a better price."
);
bestPrice = _price;
bestSupplier = msg.sender;
emit BestPriceUpdated(msg.sender, bestPrice);
}
function auctionEnd() public{
require(state == Phase.AUCTION);
if(msg.sender == consumer){
auctionEndTime = now;
state = auctionEndTime >= consumptionStartTime ? Phase.CONSUMPTION : Phase.VIOLATED;
}else if(now >= consumptionStartTime){
auctionEndTime = now;
state = Phase.CONSUMPTION;
}
}
function isValidWithdrawGain() private view returns(bool){
return state != Phase.GAIN_WITHDRAWN &&
state != Phase.COMPLETED &&
state != Phase.VIOLATED &&
state != Phase.VIOLATION_RESOLVED;
}
function isValidWithdraw() private view returns(bool){
return state != Phase.PRICE_WITHDRAWN &&
state != Phase.COMPLETED &&
state != Phase.VIOLATED &&
state != Phase.VIOLATION_RESOLVED;
}
function setEndTimes() private{
if(auctionEndTime == 0){
auctionEndTime = consumptionStartTime;
}
if(consumptionTime == 0){
consumptionTime = consumptionEndTime;
}
}
/// Withdraw the gain by the sender.
function withdrawGain() public returns (bool) {
require(msg.sender == consumer);
require(isValidWithdrawGain(), "gain can't be withdrawn");
if(now >= consumptionEndTime){
setEndTimes();
uint amount = maxPrice - bestPrice;
state = state == Phase.PRICE_WITHDRAWN || bestSupplier == address(0) ? Phase.COMPLETED : Phase.GAIN_WITHDRAWN;
msg.sender.transfer(amount);
return true;
}
return false;
}
// withdraw price of energy by the best supplier
function withdraw() public returns (bool) {
require(msg.sender == bestSupplier);
require(isValidWithdraw(), "price can't be withdrawn");
if(now >= consumptionEndTime){
setEndTimes();
uint amount = bestPrice;
state = state == Phase.GAIN_WITHDRAWN || (maxPrice - bestPrice) == 0 ? Phase.COMPLETED : Phase.PRICE_WITHDRAWN;
msg.sender.transfer(amount);
return true;
}
return false;
}
function auctionStatus() public view returns (uint,address,address,uint,uint){
return (consumptionStartTime,bestSupplier,consumer,bestPrice,consumptionEndTime);
}
function withdrawableAmount() public view returns (uint){
if(!isValidWithdraw()) return 0;
else return bestPrice;
}
function withdrawableGain() public view returns (uint){
if(!isValidWithdrawGain()) return 0;
else return maxPrice - bestPrice;
}
function consumePower() public
{
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
//1. Conditions
require(state == Phase.CONSUMPTION || state == Phase.AUCTION, "Auction has not ended yet");
//2. Effects
if(consumer == msg.sender && now < consumptionStartTime){
auctionEndTime = now;
consumptionTime = now;
state = Phase.VIOLATED;
} else if(consumer == msg.sender && now >= consumptionStartTime){
state = Phase.FINISHED;
consumptionTime = now;
emit Consumed(msg.sender, bestSupplier,requiredNRG,bestPrice);
}else if(now >= consumptionEndTime) {
consumptionTime = consumptionEndTime;
state = Phase.FINISHED;
}
}
function resolveViolation() public {
require(state == Phase.VIOLATED);
if(bestSupplier != address(0)){
bestSupplier.transfer(bestPrice);
}
consumer.transfer(maxPrice-bestPrice);
state = Phase.VIOLATION_RESOLVED;
}
function destroy() public {
// Should be a 3rd party, trusted static account
// that will resolve the payments
require(msg.sender == consumer);
selfdestruct(consumer);
}
} | Should be a 3rd party, trusted static account that will resolve the payments | function destroy() public {
require(msg.sender == consumer);
selfdestruct(consumer);
}
| 14,038,237 | [
1,
14309,
506,
279,
890,
13623,
18285,
16,
13179,
760,
2236,
716,
903,
2245,
326,
25754,
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,
5546,
1435,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
4765,
1769,
203,
3639,
365,
5489,
8813,
12,
13230,
1769,
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
] |
./full_match/1/0xcDa5d0596929Ed969fC026Cfb8F02f7ECc92DAD6/sources/SquidRise.sol | prevent overly large contract sells. | function swapBack() private lockTheSwap {
uint256 contractBalance = balanceOf(address(this));
if(contractBalance >= minimumTokensBeforeSwap * 5){
contractBalance = minimumTokensBeforeSwap * 5;
}
bool success;
uint256 totalTokensToSwap = _liquidityTokensToSwap + _buyBackTokensToSwap + _marketingTokensToSwap;
uint256 amountToSwapForBNB = contractBalance.sub(tokensForLiquidity);
uint256 initialBNBBalance = address(this).balance;
swapTokensForBNB(amountToSwapForBNB);
uint256 bnbBalance = address(this).balance.sub(initialBNBBalance);
uint256 bnbForMarketing = bnbBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap);
uint256 bnbForBuyBack = bnbBalance.mul(_buyBackTokensToSwap).div(totalTokensToSwap);
uint256 bnbForLiquidity = bnbBalance - bnbForMarketing - bnbForBuyBack;
_liquidityTokensToSwap = 0;
_marketingTokensToSwap = 0;
_buyBackTokensToSwap = 0;
if(tokensForLiquidity > 0 && bnbForLiquidity > 0){
addLiquidity(tokensForLiquidity, bnbForLiquidity);
emit SwapAndLiquify(amountToSwapForBNB, bnbForLiquidity, tokensForLiquidity);
}
}
| 2,964,251 | [
1,
29150,
1879,
715,
7876,
6835,
357,
3251,
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,
445,
7720,
2711,
1435,
3238,
2176,
1986,
12521,
288,
203,
3639,
2254,
5034,
6835,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
540,
203,
3639,
309,
12,
16351,
13937,
1545,
5224,
5157,
4649,
12521,
380,
1381,
15329,
203,
5411,
6835,
13937,
273,
5224,
5157,
4649,
12521,
380,
1381,
31,
203,
3639,
289,
203,
540,
203,
3639,
1426,
2216,
31,
203,
3639,
2254,
5034,
2078,
5157,
774,
12521,
273,
389,
549,
372,
24237,
5157,
774,
12521,
397,
389,
70,
9835,
2711,
5157,
774,
12521,
397,
389,
3355,
21747,
5157,
774,
12521,
31,
203,
540,
203,
3639,
2254,
5034,
3844,
774,
12521,
1290,
15388,
38,
273,
6835,
13937,
18,
1717,
12,
7860,
1290,
48,
18988,
24237,
1769,
203,
540,
203,
3639,
2254,
5034,
2172,
15388,
9676,
6112,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
203,
3639,
7720,
5157,
1290,
15388,
38,
12,
8949,
774,
12521,
1290,
15388,
38,
1769,
203,
540,
203,
3639,
2254,
5034,
324,
6423,
13937,
273,
1758,
12,
2211,
2934,
12296,
18,
1717,
12,
6769,
15388,
9676,
6112,
1769,
203,
540,
203,
3639,
2254,
5034,
324,
6423,
1290,
3882,
21747,
273,
324,
6423,
13937,
18,
16411,
24899,
3355,
21747,
5157,
774,
12521,
2934,
2892,
12,
4963,
5157,
774,
12521,
1769,
203,
540,
203,
3639,
2254,
5034,
324,
6423,
1290,
38,
9835,
2711,
273,
324,
6423,
13937,
18,
16411,
24899,
70,
9835,
2711,
5157,
774,
12521,
2934,
2892,
12,
4963,
5157,
774,
12521,
1769,
203,
540,
203,
540,
203,
3639,
2254,
5034,
324,
6423,
1290,
48,
18988,
24237,
273,
324,
2
] |
//SPDX-License-Identifier: MIT License
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "./DaoConfig.sol";
/**
* @dev Handles all the proposal and voting logic
*/
contract DaoStake is DaoConfig {
/**
* @dev Stake Setup
*/
struct Stake {
uint128 amount;
uint128 startTime;
}
/**
* @dev Track who is staking and how much.
*/
mapping(address => Stake) internal memberToStakedTokens;
/**
* @dev Track total staked.
*/
uint256 internal totalStaked;
constructor(string memory _name, string memory _symbol)
DaoConfig(_name, _symbol)
{}
}
| * @dev Stake Setup/ | struct Stake {
uint128 amount;
uint128 startTime;
}
constructor(string memory _name, string memory _symbol)
DaoConfig(_name, _symbol)
| 13,043,388 | [
1,
510,
911,
10939,
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,
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,
225,
1958,
934,
911,
288,
203,
565,
2254,
10392,
3844,
31,
203,
565,
2254,
10392,
8657,
31,
203,
225,
289,
203,
203,
203,
225,
3885,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
13,
203,
565,
463,
6033,
809,
24899,
529,
16,
389,
7175,
13,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
import '@openzeppelin/contracts/access/AccessControlEnumerable.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
contract Certificate is ERC721URIStorage, AccessControlEnumerable {
string public metadata;
address public institution; // institution is the ownwer of the certificate
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
bytes32 public constant REGISTRAR_ROLE = DEFAULT_ADMIN_ROLE; // DEFAULT_ADMIN_ROLE is REGISTRAR who can issue certificates
event SetMetaData(address indexed sender, string metadata);
event Issue(
address indexed sender,
address indexed receiver,
string info,
uint256 tokenId
);
constructor(
string memory name,
string memory symbol,
address creator
) ERC721(name, symbol) {
_setupRole(REGISTRAR_ROLE, msg.sender); // give the Institution contract as registrar
_setupRole(REGISTRAR_ROLE, creator); // give the creator as the first registrar
institution = msg.sender;
}
// warning: transfer registrar to new one
function setRegistrar(address newone) external onlyRole(REGISTRAR_ROLE) {
_setupRole(REGISTRAR_ROLE, newone);
}
// set the metadata of the certificate, this means the basic info of a certificate
function setMetaData(string calldata _metadata)
external
onlyRole(REGISTRAR_ROLE)
{
metadata = _metadata;
emit SetMetaData(msg.sender, metadata);
}
// issue the certificate to someone
function issue(address user, string calldata data)
external
onlyRole(REGISTRAR_ROLE)
{
_tokenIds.increment();
uint256 id = _tokenIds.current();
_mint(user, id);
_setTokenURI(id, data);
emit Issue(msg.sender, user, data, id);
}
// count issued certificates
function count() external view returns (uint256) {
return _tokenIds.current();
}
// check if tokenid exists
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, AccessControlEnumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| give the Institution contract as registrar
| _setupRole(REGISTRAR_ROLE, msg.sender); | 5,386,788 | [
1,
75,
688,
326,
657,
14278,
6835,
487,
17450,
297,
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,
3639,
389,
8401,
2996,
12,
5937,
18643,
985,
67,
16256,
16,
1234,
18,
15330,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 <0.7.0;
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
/**
* @title StableMath
* @author Stability Labs Pty. Ltd.
* @notice A library providing safe mathematical operations to multiply and
* divide with standardised precision.
* @dev Derives from OpenZeppelin's SafeMath lib and uses generic system
* wide variables for managing precision.
*/
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* @dev bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x.mul(FULL_SCALE);
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x.mul(ratio);
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled.add(RATIO_SCALE.sub(1));
// return 100..00.999e8 / 1e8 = 1e18
return ceil.div(RATIO_SCALE);
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
uint256 y = x.mul(RATIO_SCALE);
// return 1e22 / 1e12 = 1e10
return y.div(ratio);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
| * @dev Precisely divides two units, by first scaling the left hand operand. Useful for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) @param x Left hand input to division @param y Right hand input to division @return Result after multiplying the left operand by the scale, and executing the division on the right hand input./ e.g. 8e18 * 1e18 = 8e36 e.g. 8e36 / 10e18 = 8e17 | function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x.mul(FULL_SCALE);
return z.div(y);
}
| 12,548,229 | [
1,
1386,
71,
291,
2357,
3739,
4369,
2795,
4971,
16,
635,
1122,
10612,
326,
2002,
948,
9886,
18,
19256,
1377,
364,
13727,
11622,
3119,
899,
16,
277,
18,
73,
18,
1725,
73,
2643,
19,
2163,
73,
2643,
273,
8958,
9,
261,
280,
1725,
73,
4033,
13,
225,
619,
377,
13338,
948,
810,
358,
16536,
225,
677,
377,
13009,
948,
810,
358,
16536,
327,
1377,
3438,
1839,
10194,
310,
326,
2002,
9886,
635,
326,
3159,
16,
471,
2868,
11274,
326,
16536,
603,
326,
2145,
948,
810,
18,
19,
425,
18,
75,
18,
1725,
73,
2643,
225,
404,
73,
2643,
273,
1725,
73,
5718,
425,
18,
75,
18,
1725,
73,
5718,
342,
1728,
73,
2643,
273,
1725,
73,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
3739,
1386,
71,
291,
2357,
12,
11890,
5034,
619,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
998,
273,
619,
18,
16411,
12,
18111,
67,
19378,
1769,
203,
565,
327,
998,
18,
2892,
12,
93,
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
] |
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IController } from "../../interfaces/IController.sol";
import { IExchangeAdapter } from "../../interfaces/IExchangeAdapter.sol";
import { Invoke } from "../lib/Invoke.sol";
import { IDebtIssuanceModule } from "../../interfaces/IDebtIssuanceModule.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { IComptroller } from "../../interfaces/external/IComptroller.sol";
import { ICErc20 } from "../../interfaces/external/ICErc20.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title CompoundLeverageModule
* @author Set Protocol
*
* Smart contract that enables leverage trading using Compound as the lending protocol. This module allows for multiple Compound leverage positions
* in a SetToken. This does not allow borrowing of assets from Compound alone. Each asset is leveraged when using this module.
*
*
*/
contract CompoundLeverageModule is ModuleBase, ReentrancyGuard {
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
using Position for uint256;
using PreciseUnitMath for uint256;
using PreciseUnitMath for int256;
using Position for ISetToken;
using Invoke for ISetToken;
using AddressArrayUtils for address[];
/* ============ Structs ============ */
struct CompoundSettings {
address[] collateralCTokens; // Array of cToken collateral assets
address[] borrowCTokens; // Array of cToken borrow assets
address[] borrowAssets; // Array of underlying borrow assets
}
struct ActionInfo {
ISetToken setToken;
IExchangeAdapter exchangeAdapter;
uint256 setTotalSupply;
uint256 notionalSendQuantity;
uint256 minNotionalReceiveQuantity;
address collateralCTokenAsset;
address borrowCTokenAsset;
uint256 preTradeReceiveTokenBalance;
}
/* ============ Events ============ */
event LeverageIncreased(
ISetToken indexed _setToken,
address indexed _borrowAsset,
address indexed _collateralAsset,
IExchangeAdapter _exchangeAdapter,
uint256 _totalBorrowAmount,
uint256 _totalReceiveAmount,
uint256 _protocolFee
);
event LeverageDecreased(
ISetToken indexed _setToken,
address indexed _collateralAsset,
address indexed _repayAsset,
IExchangeAdapter _exchangeAdapter,
uint256 _totalRedeemAmount,
uint256 _totalRepayAmount,
uint256 _protocolFee
);
event CompGulped(
ISetToken indexed _setToken,
address indexed _collateralAsset,
IExchangeAdapter _exchangeAdapter,
uint256 _totalCompClaimed,
uint256 _totalReceiveAmount,
uint256 _protocolFee
);
event PositionsSynced(
ISetToken indexed _setToken,
address _caller
);
/* ============ Constants ============ */
// 0 index stores protocol fee % on the controller, charged in the trade function
uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0;
/* ============ State Variables ============ */
// Mapping of underlying to CToken. If ETH, then map WETH to cETH
mapping(address => address) public underlyingToCToken;
// Weth contract
address public weth;
// cETH address
address public cEther;
// Compound Comptroller contract
IComptroller public comptroller;
// COMP token address
address public compToken;
// Mapping to efficiently check if cToken market for collateral asset is valid in SetToken
mapping(ISetToken => mapping(address => bool)) public isCollateralCTokenEnabled;
// Mapping to efficiently check if cToken market for borrow asset is valid in SetToken
mapping(ISetToken => mapping(address => bool)) public isBorrowCTokenEnabled;
// Mapping of enabled collateral and borrow cTokens for syncing positions
mapping(ISetToken => CompoundSettings) internal compoundSettings;
/* ============ Constructor ============ */
/**
* Instantiate addresses. Underlying to cToken mapping is created.
*
* @param _controller Address of controller contract
* @param _compToken Address of COMP token
* @param _comptroller Address of Compound Comptroller
* @param _cEther Address of cEther contract
* @param _weth Address of WETH contract
*/
constructor(
IController _controller,
address _compToken,
IComptroller _comptroller,
address _cEther,
address _weth
)
public
ModuleBase(_controller)
{
compToken = _compToken;
comptroller = _comptroller;
cEther = _cEther;
weth = _weth;
ICErc20[] memory cTokens = comptroller.getAllMarkets();
// Loop through cTokens
for(uint256 i = 0; i < cTokens.length; i++) {
if (address(cTokens[i]) == _cEther) {
underlyingToCToken[_weth] = address(cTokens[i]);
} else {
address underlying = cTokens[i].underlying();
underlyingToCToken[underlying] = address(cTokens[i]);
}
}
}
/* ============ External Functions ============ */
/**
* Increases leverage for a given collateral position using a specified borrow asset that is enabled
*
* @param _setToken Instance of the SetToken
* @param _borrowAsset Address of asset being borrowed for leverage
* @param _collateralAsset Address of collateral asset
* @param _borrowQuantity Quantity of asset to borrow
* @param _minReceiveQuantity Minimum amount of collateral asset to receive post trade
* @param _tradeAdapterName Name of trade adapter
* @param _tradeData Arbitrary data for trade
*/
function lever(
ISetToken _setToken,
address _borrowAsset,
address _collateralAsset,
uint256 _borrowQuantity,
uint256 _minReceiveQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
// Note: for levering up, send quantity is derived from borrow asset and receive quantity is derived from
// collateral asset
ActionInfo memory leverInfo = _createActionInfo(
_setToken,
_borrowAsset,
_collateralAsset,
_borrowQuantity,
_minReceiveQuantity,
_tradeAdapterName,
true
);
_validateCommon(leverInfo);
_borrow(leverInfo.setToken, leverInfo.borrowCTokenAsset, leverInfo.notionalSendQuantity);
(uint256 protocolFee, uint256 postTradeCollateralQuantity) = _trade(
_setToken,
_borrowAsset,
_collateralAsset,
leverInfo.notionalSendQuantity,
leverInfo.minNotionalReceiveQuantity,
leverInfo.preTradeReceiveTokenBalance,
leverInfo.exchangeAdapter,
_tradeData
);
_mint(leverInfo.setToken, leverInfo.collateralCTokenAsset, _collateralAsset, postTradeCollateralQuantity);
// Update SetToken positions
_updateCollateralPosition(
leverInfo.setToken,
leverInfo.collateralCTokenAsset,
_getCollateralPosition(
leverInfo.setToken,
leverInfo.collateralCTokenAsset,
leverInfo.setTotalSupply
)
);
_updateBorrowPosition(
leverInfo.setToken,
_borrowAsset,
_getBorrowPosition(
leverInfo.setToken,
leverInfo.borrowCTokenAsset,
_borrowAsset,
leverInfo.setTotalSupply
)
);
emit LeverageIncreased(
_setToken,
_borrowAsset,
_collateralAsset,
leverInfo.exchangeAdapter,
leverInfo.notionalSendQuantity,
postTradeCollateralQuantity,
protocolFee
);
}
/**
* Increases leverage for a given collateral position using a specified borrow asset that is enabled
*
* @param _setToken Instance of the SetToken
* @param _collateralAsset Address of collateral asset
* @param _repayAsset Address of asset being repaid
* @param _redeemQuantity Quantity of collateral asset to delever
* @param _minRepayQuantity Minimum amount of repay asset to receive post trade
* @param _tradeAdapterName Name of trade adapter
* @param _tradeData Arbitrary data for trade
*/
function delever(
ISetToken _setToken,
address _collateralAsset,
address _repayAsset,
uint256 _redeemQuantity,
uint256 _minRepayQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
// Note: for levering up, send quantity is derived from collateral asset and receive quantity is derived from
// repay asset
ActionInfo memory deleverInfo = _createActionInfo(
_setToken,
_collateralAsset,
_repayAsset,
_redeemQuantity,
_minRepayQuantity,
_tradeAdapterName,
false
);
_validateCommon(deleverInfo);
_redeem(deleverInfo.setToken, deleverInfo.collateralCTokenAsset, deleverInfo.notionalSendQuantity);
(uint256 protocolFee, uint256 postTradeRepayQuantity) = _trade(
_setToken,
_collateralAsset,
_repayAsset,
deleverInfo.notionalSendQuantity,
deleverInfo.minNotionalReceiveQuantity,
deleverInfo.preTradeReceiveTokenBalance,
deleverInfo.exchangeAdapter,
_tradeData
);
_repay(deleverInfo.setToken, deleverInfo.borrowCTokenAsset, _repayAsset, postTradeRepayQuantity);
// Update SetToken positions
_updateCollateralPosition(
deleverInfo.setToken,
deleverInfo.collateralCTokenAsset,
_getCollateralPosition(deleverInfo.setToken, deleverInfo.collateralCTokenAsset, deleverInfo.setTotalSupply)
);
_updateBorrowPosition(
deleverInfo.setToken,
_repayAsset,
_getBorrowPosition(deleverInfo.setToken, deleverInfo.borrowCTokenAsset, _repayAsset, deleverInfo.setTotalSupply)
);
emit LeverageDecreased(
_setToken,
_collateralAsset,
_repayAsset,
deleverInfo.exchangeAdapter,
deleverInfo.notionalSendQuantity,
postTradeRepayQuantity,
protocolFee
);
}
/**
* Claims COMP and trades for specified collateral asset
*
* @param _setToken Instance of the SetToken
* @param _collateralAsset Address of collateral asset
* @param _minNotionalReceiveQuantity Minimum total amount of collateral asset to receive post trade
* @param _tradeAdapterName Name of trade adapter
* @param _tradeData Arbitrary data for trade
*/
function gulp(
ISetToken _setToken,
address _collateralAsset,
uint256 _minNotionalReceiveQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
ActionInfo memory gulpInfo = _createGulpInfoAndClaim(
_setToken,
_collateralAsset,
_tradeAdapterName
);
uint256 protocolFee = 0;
uint256 postTradeCollateralQuantity;
// Skip trade if collateral asset is COMP
if (_collateralAsset != compToken) {
require(gulpInfo.notionalSendQuantity > 0, "Token to sell must be nonzero");
(protocolFee, postTradeCollateralQuantity) = _trade(
_setToken,
compToken,
_collateralAsset,
gulpInfo.notionalSendQuantity,
_minNotionalReceiveQuantity,
gulpInfo.preTradeReceiveTokenBalance,
gulpInfo.exchangeAdapter,
_tradeData
);
} else {
postTradeCollateralQuantity = gulpInfo.preTradeReceiveTokenBalance;
}
_mint(_setToken, gulpInfo.collateralCTokenAsset, _collateralAsset, postTradeCollateralQuantity);
// Update SetToken positions
_updateCollateralPosition(
_setToken,
gulpInfo.collateralCTokenAsset,
_getCollateralPosition(_setToken, gulpInfo.collateralCTokenAsset, gulpInfo.setTotalSupply)
);
emit CompGulped(
_setToken,
_collateralAsset,
gulpInfo.exchangeAdapter,
gulpInfo.notionalSendQuantity,
postTradeCollateralQuantity,
protocolFee
);
}
/**
* Sync Set positions with Compound
*
* @param _setToken Instance of the SetToken
*/
function sync(ISetToken _setToken) public nonReentrant onlyValidAndInitializedSet(_setToken) {
uint256 setTotalSupply = _setToken.totalSupply();
// Loop through collateral assets
for(uint i = 0; i < compoundSettings[_setToken].collateralCTokens.length; i++) {
address collateralCToken = compoundSettings[_setToken].collateralCTokens[i];
uint256 previousPositionUnit = _setToken.getDefaultPositionRealUnit(collateralCToken).toUint256();
uint256 newPositionUnit = _getCollateralPosition(_setToken, collateralCToken, setTotalSupply);
// If position units changed, then update. E.g. Position liquidated, and collateral position is in fact
// less than what is tracked
// Note: Accounts for if position does not exist on SetToken but is tracked in compoundSettings
if (previousPositionUnit != newPositionUnit) {
_updateCollateralPosition(_setToken, collateralCToken, newPositionUnit);
}
}
// Loop through borrow assets
for(uint i = 0; i < compoundSettings[_setToken].borrowCTokens.length; i++) {
address borrowCToken = compoundSettings[_setToken].borrowCTokens[i];
address borrowAsset = compoundSettings[_setToken].borrowAssets[i];
int256 previousPositionUnit = _setToken.getExternalPositionRealUnit(borrowAsset, address(this));
int256 newPositionUnit = _getBorrowPosition(
_setToken,
borrowCToken,
borrowAsset,
setTotalSupply
);
// If position units changed, then update. E.g. Interest is accrued or position is liquidated
// and borrow position is repaid
// Note: Accounts for if position does not exist on SetToken but is tracked in compoundSettings
if (newPositionUnit != previousPositionUnit) {
_updateBorrowPosition(_setToken, borrowAsset, newPositionUnit);
}
}
emit PositionsSynced(_setToken, msg.sender);
}
/**
* Initializes this module to the SetToken. Only callable by the SetToken's manager. Note: managers can enable
* collateral and borrow assets that don't exist as positions on the SetToken
*
* @param _setToken Instance of the SetToken to initialize
* @param _collateralAssets Underlying tokens to be enabled as collateral in the SetToken
* @param _borrowAssets Underlying tokens to be enabled as borrow in the SetToken
*/
function initialize(
ISetToken _setToken,
address[] memory _collateralAssets,
address[] memory _borrowAssets
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
address[] memory collateralCTokens = new address[](_collateralAssets.length);
// Loop through collateral assets and set mapping
for(uint256 i = 0; i < _collateralAssets.length; i++) {
address cTokenAddress;
if (_collateralAssets[i] == weth) {
// Set as cETH if asset is WETH
cTokenAddress = cEther;
} else {
cTokenAddress = underlyingToCToken[_collateralAssets[i]];
require(cTokenAddress != address(0), "cToken must exist in Compound");
}
isCollateralCTokenEnabled[_setToken][cTokenAddress] = true;
collateralCTokens[i] = cTokenAddress;
}
compoundSettings[_setToken].collateralCTokens = collateralCTokens;
address[] memory borrowCTokens = new address[](_borrowAssets.length);
// Loop through borrow assets
for(uint256 i = 0; i < _borrowAssets.length; i++) {
address cTokenAddress;
if (_borrowAssets[i] == weth) {
// Set as cETH if asset is WETH
cTokenAddress = cEther;
} else {
cTokenAddress = underlyingToCToken[_borrowAssets[i]];
require(cTokenAddress != address(0), "cToken must exist in Compound");
}
isBorrowCTokenEnabled[_setToken][cTokenAddress] = true;
borrowCTokens[i] = cTokenAddress;
}
compoundSettings[_setToken].borrowCTokens = borrowCTokens;
compoundSettings[_setToken].borrowAssets = _borrowAssets;
// Initialize module before trying register
_setToken.initializeModule();
// Try if register exists on any of the modules
syncRegister(_setToken);
// Enable collateral and borrow assets on Compound. Note: if there is overlap between borrow cTokens and collateral cTokens, markets are entered with no issue
_enterMarkets(_setToken, collateralCTokens);
_enterMarkets(_setToken, borrowCTokens);
}
/**
* Removes this module from the SetToken, via call by the SetToken. Compound Settings and manager enabled
* cTokens are deleted
*/
function removeModule() external override {
ISetToken setToken = ISetToken(msg.sender);
for (uint256 i = 0; i < compoundSettings[setToken].borrowCTokens.length; i++) {
address cToken = compoundSettings[setToken].borrowCTokens[i];
// Note: if there is an existing borrow balance, will revert and market cannot be exited on Compound
_exitMarket(setToken, cToken);
delete isBorrowCTokenEnabled[setToken][cToken];
}
for (uint256 i = 0; i < compoundSettings[setToken].collateralCTokens.length; i++) {
address cToken = compoundSettings[setToken].collateralCTokens[i];
_exitMarket(setToken, cToken);
delete isCollateralCTokenEnabled[setToken][cToken];
}
delete compoundSettings[setToken];
// Try if unregister exists on any of the modules
address[] memory modules = setToken.getModules();
for(uint256 i = 0; i < modules.length; i++) {
try IDebtIssuanceModule(modules[i]).unregister(setToken) {} catch {}
}
}
/**
* Sync Compound markets with stored underlying to cToken mapping. Anyone callable
*/
function syncCompoundMarkets() external {
ICErc20[] memory cTokens = comptroller.getAllMarkets();
// Loop through cTokens
for(uint256 i = 0; i < cTokens.length; i++) {
if (address(cTokens[i]) != cEther) {
address underlying = cTokens[i].underlying();
// If cToken is not in mapping, then add it
if (underlyingToCToken[underlying] == address(0)) {
underlyingToCToken[underlying] = address(cTokens[i]);
}
}
}
}
/**
* Sync registration of this module on SetToken. Anyone callable
*
* @param _setToken Instance of the SetToken
*/
function syncRegister(ISetToken _setToken) public onlyValidAndInitializedSet(_setToken) {
address[] memory modules = _setToken.getModules();
for(uint256 i = 0; i < modules.length; i++) {
try IDebtIssuanceModule(modules[i]).register(_setToken) {} catch {}
}
}
function addCollateralAsset(ISetToken _setToken, address _newCollateralAsset) external onlyManagerAndValidSet(_setToken) {
address cToken = underlyingToCToken[_newCollateralAsset];
require(cToken != address(0), "cToken must exist in Compound");
require(!isCollateralCTokenEnabled[_setToken][cToken], "Collateral cToken is already enabled");
// Note: Will only enter market if cToken is not enabled as a borrow asset as well
if (!isBorrowCTokenEnabled[_setToken][cToken]) {
address[] memory marketsToEnter = new address[](1);
marketsToEnter[0] = cToken;
_enterMarkets(_setToken, marketsToEnter);
}
isCollateralCTokenEnabled[_setToken][cToken] = true;
compoundSettings[_setToken].collateralCTokens.push(cToken);
}
function removeCollateralAsset(ISetToken _setToken, address _collateralAsset) external onlyManagerAndValidSet(_setToken) {
address cToken = underlyingToCToken[_collateralAsset];
require(isCollateralCTokenEnabled[_setToken][cToken], "Collateral cToken is already not enabled");
// Note: Will only exit market if cToken is not enabled as a borrow asset as well
if (!isBorrowCTokenEnabled[_setToken][cToken]) {
_exitMarket(_setToken, cToken);
}
isCollateralCTokenEnabled[_setToken][cToken] = false;
compoundSettings[_setToken].collateralCTokens = compoundSettings[_setToken].collateralCTokens.remove(cToken);
}
function addBorrowAsset(ISetToken _setToken, address _newBorrowAsset) external onlyManagerAndValidSet(_setToken) {
address cToken = underlyingToCToken[_newBorrowAsset];
require(cToken != address(0), "cToken must exist in Compound");
require(!isBorrowCTokenEnabled[_setToken][cToken], "Borrow cToken is already enabled");
// Note: Will only enter market if cToken is not enabled as a borrow asset as well
if (!isCollateralCTokenEnabled[_setToken][cToken]) {
address[] memory marketsToEnter = new address[](1);
marketsToEnter[0] = cToken;
_enterMarkets(_setToken, marketsToEnter);
}
isBorrowCTokenEnabled[_setToken][cToken] = true;
compoundSettings[_setToken].borrowCTokens.push(cToken);
compoundSettings[_setToken].borrowAssets.push(_newBorrowAsset);
}
function removeBorrowAsset(ISetToken _setToken, address _borrowAsset) external onlyManagerAndValidSet(_setToken) {
address cToken = underlyingToCToken[_borrowAsset];
require(isBorrowCTokenEnabled[_setToken][cToken], "Borrow cToken is already not enabled");
// Note: Will only exit market if cToken is not enabled as a collateral asset as well
// If there is an existing borrow balance, will revert and market cannot be exited on Compound
if (!isCollateralCTokenEnabled[_setToken][cToken]) {
_exitMarket(_setToken, cToken);
}
isBorrowCTokenEnabled[_setToken][cToken] = false;
compoundSettings[_setToken].borrowCTokens = compoundSettings[_setToken].borrowCTokens.remove(cToken);
compoundSettings[_setToken].borrowAssets = compoundSettings[_setToken].borrowAssets.remove(_borrowAsset);
}
function moduleIssueHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external onlyModule(_setToken) {
sync(_setToken);
}
function moduleRedeemHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external onlyModule(_setToken) {
sync(_setToken);
}
function componentIssueHook(ISetToken _setToken, uint256 _setTokenQuantity, address _component) external onlyModule(_setToken) {
int256 componentDebt = _setToken.getExternalPositionRealUnit(_component, address(this));
uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMul(_setTokenQuantity);
address cToken = underlyingToCToken[_component];
_borrow(_setToken, cToken, notionalDebt);
}
function componentRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity, address _component) external onlyModule(_setToken) {
int256 componentDebt = _setToken.getExternalPositionRealUnit(_component, address(this));
uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMul(_setTokenQuantity);
address cToken = underlyingToCToken[_component];
_repay(_setToken, cToken, _component, notionalDebt);
}
/* ============ External Getter Functions ============ */
function getEnabledCollateralCTokens(ISetToken _setToken) external view returns(address[] memory) {
return compoundSettings[_setToken].collateralCTokens;
}
function getEnabledBorrowCTokens(ISetToken _setToken) external view returns(address[] memory) {
return compoundSettings[_setToken].borrowCTokens;
}
function getEnabledBorrowAssets(ISetToken _setToken) external view returns(address[] memory) {
return compoundSettings[_setToken].borrowAssets;
}
/* ============ Internal Functions ============ */
/**
* Construct the ActionInfo struct for lever and delever
*/
function _createActionInfo(
ISetToken _setToken,
address _sendToken,
address _receiveToken,
uint256 _sendQuantity,
uint256 _minReceiveQuantity,
string memory _tradeAdapterName,
bool isLever
)
internal
view
returns(ActionInfo memory)
{
ActionInfo memory actionInfo;
actionInfo.exchangeAdapter = IExchangeAdapter(getAndValidateAdapter(_tradeAdapterName));
actionInfo.setToken = _setToken;
actionInfo.collateralCTokenAsset = isLever ? underlyingToCToken[_receiveToken] : underlyingToCToken[_sendToken];
actionInfo.borrowCTokenAsset = isLever ? underlyingToCToken[_sendToken] : underlyingToCToken[_receiveToken];
actionInfo.setTotalSupply = _setToken.totalSupply();
actionInfo.notionalSendQuantity = _sendQuantity.preciseMul(actionInfo.setTotalSupply);
actionInfo.minNotionalReceiveQuantity = _minReceiveQuantity.preciseMul(actionInfo.setTotalSupply);
// Snapshot pre trade receive token balance.
actionInfo.preTradeReceiveTokenBalance = IERC20(_receiveToken).balanceOf(address(_setToken));
return actionInfo;
}
/**
* Construct the ActionInfo struct for gulp
*/
function _createGulpInfoAndClaim(
ISetToken _setToken,
address _collateralAsset,
string memory _tradeAdapterName
)
internal
returns(ActionInfo memory)
{
ActionInfo memory actionInfo;
actionInfo.collateralCTokenAsset = underlyingToCToken[_collateralAsset];
require(isCollateralCTokenEnabled[_setToken][actionInfo.collateralCTokenAsset], "Collateral cToken is not enabled");
actionInfo.exchangeAdapter = IExchangeAdapter(getAndValidateAdapter(_tradeAdapterName));
actionInfo.setTotalSupply = _setToken.totalSupply();
// Snapshot COMP balances pre claim
uint256 preClaimCompBalance = IERC20(compToken).balanceOf(address(_setToken));
// Claim COMP
_claim(_setToken);
// Snapshot pre trade receive token balance.
actionInfo.preTradeReceiveTokenBalance = IERC20(_collateralAsset).balanceOf(address(_setToken));
// Calculate notional send quantity
actionInfo.notionalSendQuantity = IERC20(compToken).balanceOf(address(_setToken)).sub(preClaimCompBalance);
return actionInfo;
}
function _validateCommon(ActionInfo memory _actionInfo) internal view {
require(isCollateralCTokenEnabled[_actionInfo.setToken][_actionInfo.collateralCTokenAsset], "Collateral cToken is not enabled");
require(isBorrowCTokenEnabled[_actionInfo.setToken][_actionInfo.borrowCTokenAsset], "Borrow cToken is not enabled");
require(_actionInfo.collateralCTokenAsset != _actionInfo.borrowCTokenAsset, "Collateral and borrow assets must be different");
require(_actionInfo.notionalSendQuantity > 0, "Token to sell must be nonzero");
}
/**
* Invoke enter markets from SetToken
*/
function _enterMarkets(ISetToken _setToken, address[] memory _cTokens) internal {
// enterMarkets(address[] _cTokens)
bytes memory enterMarketsCallData = abi.encodeWithSignature("enterMarkets(address[])", _cTokens);
uint256[] memory returnValues = abi.decode(
_setToken.invoke(address(comptroller), 0, enterMarketsCallData),
(uint256[])
);
for (uint256 i = 0; i < _cTokens.length; i++) {
require(
returnValues[i] == 0,
"Entering market failed"
);
}
}
/**
* Invoke exit market from SetToken
*/
function _exitMarket(ISetToken _setToken, address _cToken) internal {
// exitMarket(address _cToken)
bytes memory exitMarketCallData = abi.encodeWithSignature("exitMarket(address)", _cToken);
require(
abi.decode(_setToken.invoke(address(comptroller), 0, exitMarketCallData), (uint256)) == 0,
"Exiting market failed"
);
}
/**
* Invoke mint from SetToken
*/
function _mint(ISetToken _setToken, address _cToken, address _underlyingToken, uint256 _mintNotional) internal {
if (_cToken == cEther) {
_setToken.invokeUnwrapWETH(weth, _mintNotional);
// mint(). No return, reverts on error.
bytes memory mintCEthCallData = abi.encodeWithSignature("mint()");
_setToken.invoke(_cToken, _mintNotional, mintCEthCallData);
} else {
// Approve to cToken
_setToken.invokeApprove(_underlyingToken, _cToken, _mintNotional);
// mint(uint256 _mintAmount). Returns 0 if success
bytes memory mintCallData = abi.encodeWithSignature("mint(uint256)", _mintNotional);
require(
abi.decode(_setToken.invoke(_cToken, 0, mintCallData), (uint256)) == 0,
"Mint failed"
);
}
}
/**
* Invoke redeem from SetToken
*/
function _redeem(ISetToken _setToken, address _cToken, uint256 _redeemNotional) internal {
// redeemUnderlying(uint256 _underlyingAmount)
bytes memory redeemCallData = abi.encodeWithSignature("redeemUnderlying(uint256)", _redeemNotional);
require(
abi.decode(_setToken.invoke(_cToken, 0, redeemCallData), (uint256)) == 0,
"Redeem failed"
);
if (_cToken == cEther) {
_setToken.invokeWrapWETH(weth, _redeemNotional);
}
}
/**
* Invoke repay from SetToken
*/
function _repay(ISetToken _setToken, address _cToken, address _underlyingToken, uint256 _repayNotional) internal {
if (_cToken == cEther) {
_setToken.invokeUnwrapWETH(weth, _repayNotional);
// repay(). No return, revert on fail
bytes memory repayCEthCallData = abi.encodeWithSignature("repayBorrow()");
_setToken.invoke(_cToken, _repayNotional, repayCEthCallData);
} else {
// Approve to cToken
_setToken.invokeApprove(_underlyingToken, _cToken, _repayNotional);
// repay(uint256 _repayAmount)
bytes memory repayCallData = abi.encodeWithSignature("repayBorrow(uint256)", _repayNotional);
require(
abi.decode(_setToken.invoke(_cToken, 0, repayCallData), (uint256)) == 0,
"Repay failed"
);
}
}
/**
* Invoke borrow from SetToken
*/
function _borrow(ISetToken _setToken, address _cToken, uint256 _notionalBorrowQuantity) internal {
// borrow(uint256 _borrowAmount). Note: Notional borrow quantity is in units of underlying asset
bytes memory borrowCallData = abi.encodeWithSignature("borrow(uint256)", _notionalBorrowQuantity);
require(
abi.decode(_setToken.invoke(_cToken, 0, borrowCallData), (uint256)) == 0,
"Borrow failed"
);
if (_cToken == cEther) {
_setToken.invokeWrapWETH(weth, _notionalBorrowQuantity);
}
}
/**
* Invoke trade from SetToken
*/
function _trade(
ISetToken _setToken,
address _sendToken,
address _receiveToken,
uint256 _notionalSendQuantity,
uint256 _minNotionalReceiveQuantity,
uint256 _preTradeReceiveTokenBalance,
IExchangeAdapter _exchangeAdapter,
bytes memory _data
)
internal
returns(uint256, uint256)
{
_executeTrade(
_setToken,
_sendToken,
_receiveToken,
_notionalSendQuantity,
_minNotionalReceiveQuantity,
_exchangeAdapter,
_data
);
uint256 receiveTokenQuantity = IERC20(_receiveToken).balanceOf(address(_setToken)).sub(_preTradeReceiveTokenBalance);
require(
receiveTokenQuantity >= _minNotionalReceiveQuantity,
"Slippage greater than allowed"
);
// Accrue protocol fee
uint256 protocolFeeTotal = _accrueProtocolFee(_setToken, _receiveToken, receiveTokenQuantity);
return (protocolFeeTotal, receiveTokenQuantity.sub(protocolFeeTotal));
}
function _executeTrade(
ISetToken _setToken,
address _sendToken,
address _receiveToken,
uint256 _notionalSendQuantity,
uint256 _minNotionalReceiveQuantity,
IExchangeAdapter _exchangeAdapter,
bytes memory _data
)
internal
{
_setToken.invokeApprove(
_sendToken,
_exchangeAdapter.getSpender(),
_notionalSendQuantity
);
(
address targetExchange,
uint256 callValue,
bytes memory methodData
) = _exchangeAdapter.getTradeCalldata(
_sendToken,
_receiveToken,
address(_setToken),
_notionalSendQuantity,
_minNotionalReceiveQuantity,
_data
);
_setToken.invoke(targetExchange, callValue, methodData);
}
function _accrueProtocolFee(ISetToken _setToken, address _receiveToken, uint256 _exchangedQuantity) internal returns(uint256) {
// Accrue protocol fee
uint256 protocolFeeTotal = getModuleFee(PROTOCOL_TRADE_FEE_INDEX, _exchangedQuantity);
payProtocolFeeFromSetToken(_setToken, _receiveToken, protocolFeeTotal);
return protocolFeeTotal;
}
/**
* Invoke claim COMP from SetToken
*/
function _claim(ISetToken _setToken) internal {
// claimComp(address _holder)
bytes memory claimCallData = abi.encodeWithSignature("claimComp(address)", address(_setToken));
_setToken.invoke(address(comptroller), 0, claimCallData);
}
function _getCollateralPosition(ISetToken _setToken, address _cToken, uint256 _setTotalSupply) internal view returns (uint256) {
uint256 collateralNotionalBalance = IERC20(_cToken).balanceOf(address(_setToken));
return collateralNotionalBalance.preciseDiv(_setTotalSupply);
}
function _getBorrowPosition(ISetToken _setToken, address _cToken, address _underlyingToken, uint256 _setTotalSupply) internal returns (int256) {
uint256 borrowNotionalBalance = ICErc20(_cToken).borrowBalanceCurrent(address(_setToken));
// Round negative away from 0
return borrowNotionalBalance.preciseDivCeil(_setTotalSupply).toInt256().mul(-1);
}
function _updateCollateralPosition(ISetToken _setToken, address _cToken, uint256 _newPositionUnit) internal {
_setToken.editDefaultPosition(_cToken, _newPositionUnit);
}
function _updateBorrowPosition(ISetToken _setToken, address _underlyingToken, int256 _newPositionUnit) internal {
_setToken.editExternalPosition(_underlyingToken, address(this), _newPositionUnit, "");
}
} | Loop through cTokens | {
compToken = _compToken;
comptroller = _comptroller;
cEther = _cEther;
weth = _weth;
ICErc20[] memory cTokens = comptroller.getAllMarkets();
for(uint256 i = 0; i < cTokens.length; i++) {
if (address(cTokens[i]) == _cEther) {
underlyingToCToken[_weth] = address(cTokens[i]);
address underlying = cTokens[i].underlying();
underlyingToCToken[underlying] = address(cTokens[i]);
}
}
}
| 14,071,395 | [
1,
6452,
3059,
276,
5157,
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,
288,
203,
3639,
1161,
1345,
273,
389,
2919,
1345,
31,
203,
3639,
532,
337,
1539,
273,
389,
832,
337,
1539,
31,
203,
3639,
276,
41,
1136,
273,
389,
71,
41,
1136,
31,
203,
3639,
341,
546,
273,
389,
91,
546,
31,
203,
203,
3639,
467,
1441,
1310,
3462,
8526,
3778,
276,
5157,
273,
532,
337,
1539,
18,
588,
1595,
3882,
2413,
5621,
203,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
276,
5157,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
2867,
12,
71,
5157,
63,
77,
5717,
422,
389,
71,
41,
1136,
13,
288,
203,
7734,
6808,
774,
1268,
969,
63,
67,
91,
546,
65,
273,
1758,
12,
71,
5157,
63,
77,
19226,
203,
7734,
1758,
6808,
273,
276,
5157,
63,
77,
8009,
9341,
6291,
5621,
203,
7734,
6808,
774,
1268,
969,
63,
9341,
6291,
65,
273,
1758,
12,
71,
5157,
63,
77,
19226,
203,
5411,
289,
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
] |
./full_match/137/0x335fF3edFb787e24fd6F3eB6c5E6e53003017cdD/sources/contracts/notlarvalads.sol | * @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(address => mapping(uint256 => uint256)) private _ownedTokens;
mapping(uint256 => uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 => uint256) private _allTokensIndex;
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns(bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
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];
}
function totalSupply() public view virtual override returns(uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 index) public view virtual override returns(uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
}
} else if (from != to) {
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
}
} else if (to != from) {
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId;
_allTokensIndex[lastTokenId] = tokenIndex;
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
| 4,735,382 | [
1,
2503,
4792,
392,
3129,
2710,
434,
288,
654,
39,
27,
5340,
97,
2553,
316,
326,
512,
2579,
716,
4831,
3557,
2967,
434,
777,
326,
1147,
3258,
316,
326,
6835,
487,
5492,
487,
777,
1147,
3258,
16199,
635,
1517,
2236,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
17801,
6835,
4232,
39,
27,
5340,
3572,
25121,
353,
4232,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
3572,
25121,
288,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
3238,
389,
995,
329,
5157,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
3238,
389,
995,
329,
5157,
1016,
31,
203,
565,
2254,
5034,
8526,
3238,
389,
454,
5157,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
3238,
389,
454,
5157,
1016,
31,
203,
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,
97,
203,
203,
97,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
45,
654,
39,
28275,
16,
4232,
39,
27,
5340,
13,
1135,
12,
6430,
13,
288,
203,
3639,
327,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
3572,
25121,
2934,
5831,
548,
747,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
1147,
951,
5541,
21268,
12,
2867,
3410,
16,
2254,
5034,
770,
13,
1071,
1476,
5024,
3849,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
1615,
411,
4232,
39,
27,
5340,
18,
12296,
951,
12,
8443,
3631,
315,
654,
39,
27,
5340,
3572,
25121,
30,
3410,
770,
596,
434,
4972,
8863,
203,
3639,
327,
389,
995,
329,
5157,
63,
8443,
6362,
1615,
15533,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
2
] |
pragma solidity ^0.4.18;
interface TokenStagesManager {
function isDebug() public constant returns(bool);
function setToken(address tokenAddress) public;
function getPool() public constant returns (uint96);
function getBonus() public constant returns (uint8);
function isFreezeTimeout() public constant returns (bool);
function isTimeout() public constant returns (bool);
function isICO() public view returns(bool);
function isCanList() public view returns (bool);
function calculateBonus(uint96 amount) public view returns (uint88);
function delegateFromPool(uint96 amount) public;
function delegateFromBonus(uint88 amount) public;
function delegateFromReferral(uint88 amount) public;
function getBonusPool() public constant returns(uint88);
function getReferralPool() public constant returns(uint88);
}
contract Administrated {
address public administrator;
modifier onlyAdministrator() {
require(administrator == tx.origin);
_;
}
modifier notAdministrator() {
require(administrator != tx.origin);
_;
}
function setAdministrator(address _administrator)
internal
{
administrator = _administrator;
}
}
//-------//
contract UNITStagesManager is TokenStagesManager, Administrated {
struct StageOffer {
uint96 pool;
uint8 bonus;
}
struct Stage {
uint32 startsAt;
uint32 endsAt;
StageOffer[5] offers;
}
uint88 public bonusPool = 14322013755263720000000000; //
uint88 public referralPool = 34500000000000000000000000; //34.5mln
Stage[3] public stages;
uint8 public stage;
uint8 public offer = 0;
UNITv2 public token;
bool internal _isDebug;
event StageUpdated(uint8 prevStage, uint8 prefOffer, uint8 newStage, uint8 newOffer);
event TokensDelegated(uint96 amount, uint88 bonus);
event ReferralTokensDelegated(uint96 amount);
event BonusTokensDelegated(uint96 amount);
modifier tokenOrAdmin() {
require(tx.origin == administrator || (address(token) != address(0) && msg.sender == address(token)));
_;
}
modifier onlyDebug() {
require(_isDebug);
_;
}
modifier canDelegate() {
require(msg.sender == address(token) || (_isDebug && tx.origin == administrator));
_;
}
function UNITStagesManager(bool isDebug, address _token)
public
{
setAdministrator(tx.origin);
token = UNITv2(_token);
_isDebug = isDebug;
if (!_isDebug) {
switchStage();
}
buildPreICOStage();
buildICOStageOne();
buildICOStageTwo();
}
function isDebug()
public
constant
returns (bool)
{
return _isDebug;
}
function buildPreICOStage()
internal
{
stages[0].startsAt = 1515610800; //10th of January 2018 at 19:00UTC
stages[0].endsAt = 1518894000; //17th of February 2018 at 19:00UTC
stages[0].offers[0].pool = 24705503438815932384141049; //25 mln tokens
stages[0].offers[0].bonus = 40;
}
function buildICOStageOne()
internal
{
stages[1].startsAt = 1519326000; //22th of February 2018 at 19:00UTC
stages[1].endsAt = 1521745200; //22th of March 2018 at 19:00UTC
stages[1].offers[0].pool = 5000000 * ( 10**18 ); //5 mln tokens
stages[1].offers[0].bonus = 35; //35%
stages[1].offers[1].pool = 5000000 * ( 10**18 ); //5 mln tokens
stages[1].offers[1].bonus = 30; //30%
stages[1].offers[2].pool = 5000000 * ( 10**18 ); //5 mln tokens
stages[1].offers[2].bonus = 25; //25%
stages[1].offers[3].pool = 5000000 * ( 10**18 ); //5 mln tokens
stages[1].offers[3].bonus = 20; //20%
stages[1].offers[4].pool = 122500000 * ( 10**18 ); //122.5 mln tokens
stages[1].offers[4].bonus = 0; //0%
}
function buildICOStageTwo()
internal
{
stages[2].startsAt = 1524250800; //20th of April 2018 at 19:00UTC
stages[2].endsAt = 1526842800; //20th of May 2018 at 19:00UTC
stages[2].offers[0].pool = 142794496561184067615858951;
stages[2].offers[0].bonus = 0; //0%
}
function switchStage()
public
{
uint8 _stage = stage;
uint8 _offer = 0;
while( stages.length > _stage ) {
if (stages[_stage].endsAt <= uint32(now)) {
_stage += 1;
_offer = 0;
continue;
}
while ( stages[_stage].offers.length > _offer ) {
if (stages[_stage].offers[_offer].pool == 0) {
_offer += 1;
} else {
break;
}
}
if (stages[_stage].offers.length <= _offer) {
_stage += 1;
_offer = 0;
continue;
}
break;
}
if (stage < _stage) {
migratePool();
}
StageUpdated(stage, offer, _stage, _offer);
stage = _stage;
offer = _offer;
}
function migratePool()
internal
{
if ( stage < (stages.length - 1) ) {
for (uint8 i = 0; i < stages[stage].offers.length; i++) {
stages[stages.length - 1].offers[0].pool += stages[stage].offers[i].pool;
stages[stage].offers[offer].pool = 0;
}
}
}
//START Debug methods
/*
WARNING! This methods are for debug purpose only during testing.
They will work only of isDebug option is set to true.
*/
function dTimeoutCurrentStage()
public
onlyAdministrator
onlyDebug
{
stages[stage].endsAt = uint32(now) - 10;
}
function dStartsNow()
public
onlyAdministrator
onlyDebug
{
uint32 timeDiff = stages[stage].endsAt - stages[stage].startsAt;
stages[stage].startsAt = uint32(now);
stages[stage].endsAt = stages[stage].startsAt + timeDiff;
}
function dNextStage(uint32 startOffset)
public
onlyAdministrator
onlyDebug
{
if ( stage < stages.length ) {
dTimeoutCurrentStage();
uint8 newStage = stage + 1;
uint32 timeDiff = stages[newStage].endsAt - stages[newStage].startsAt;
stages[newStage].startsAt = uint32(now) + startOffset;
stages[newStage].endsAt = stages[newStage].startsAt + timeDiff;
switchStage();
}
}
function dNextOffer()
public
onlyAdministrator
onlyDebug
{
offer++;
}
function dAlterPull(uint96 numTokens)
public
onlyAdministrator
onlyDebug
{
withdrawTokensFromPool(numTokens);
}
function dGetPool(uint8 _stage, uint8 _offer)
public
onlyAdministrator
onlyDebug
view
returns (uint96)
{
return stages[_stage].offers[_offer].pool;
}
//END Debug methods
function withdrawTokensFromPool(uint96 numTokens)
internal
{
require(numTokens <= stages[stage].offers[offer].pool);
stages[stage].offers[offer].pool -= numTokens;
}
function getCurrentStage()
public
view
returns (uint32 startsAt, uint32 endsAt, uint96 pool, uint8 bonus)
{
uint8 _stage = stage;
uint8 _offer = offer;
if ( _stage >= stages.length ) {
_stage = uint8(stages.length - 1);
_offer = 0;
}
startsAt = stages[_stage].startsAt;
endsAt = stages[_stage].endsAt;
pool = stages[_stage].offers[_offer].pool;
bonus = stages[_stage].offers[_offer].bonus;
}
function setToken(address tokenAddress)
public
onlyAdministrator
{
token = UNITv2(tokenAddress);
}
function getPool()
public
constant
returns (uint96)
{
uint8 _stage = stage;
uint8 _offer = offer;
if ( !isICO() ) {
_stage = uint8(stages.length - 1);
_offer = 0;
}
return stages[_stage].offers[_offer].pool;
}
function getBonus()
public
constant
returns (uint8)
{
uint8 _stage = stage;
uint8 _offer = offer;
if ( !isICO() ) {
_stage = uint8(stages.length - 1);
_offer = 0;
}
return stages[_stage].offers[_offer].bonus;
}
function isTimeout()
public
constant
returns (bool)
{
uint8 _stage = stage;
if ( !isICO() ) {
_stage = uint8(stages.length - 1);
}
return now >= stages[_stage].endsAt;
}
function isFreezeTimeout()
public
constant
returns (bool)
{
return now >= (stages[stages.length - 1].endsAt + 180 days);
}
function isICO()
public
constant
returns(bool)
{
return stage < stages.length;
}
function isCanList()
public
constant
returns (bool)
{
return !isICO();
}
function getBonusPool()
public
constant
returns(uint88)
{
return bonusPool;
}
function getReferralPool()
public
constant
returns(uint88)
{
return referralPool;
}
function calculateBonus(uint96 amount)
public
view
returns (uint88 bonus)
{
bonus = uint88( ( amount * getBonus() ) / 100);
if (bonus > bonusPool) {
bonus = bonusPool;
}
}
function delegateFromPool(uint96 amount)
public
canDelegate()
{
require(amount <= getPool());
uint88 bonus = calculateBonus(amount);
stages[stage].offers[offer].pool -= amount;
bonusPool -= bonus;
TokensDelegated(amount, bonus);
}
function delegateFromBonus(uint88 amount)
public
canDelegate()
{
require(amount <= getBonusPool());
bonusPool -= amount;
BonusTokensDelegated(amount);
}
function delegateFromReferral(uint88 amount)
public
canDelegate()
{
require(amount <= getReferralPool());
referralPool -= amount;
ReferralTokensDelegated(amount);
}
}
//-------//
interface Whitelist {
function add(address _wlAddress) public;
function addBulk(address[] _wlAddresses) public;
function remove(address _wlAddresses) public;
function removeBulk(address[] _wlAddresses) public;
function getAll() public constant returns(address[]);
function isInList(address _checkAddress) public constant returns(bool);
}
interface ERC20 {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function totalSupply() public constant returns (uint);
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
}
contract ERC20Contract is ERC20 {
//Token symbol
string public constant symbol = "UNIT";
//Token name
string public constant name = "Unilot token";
//It can be reeeealy small
uint8 public constant decimals = 18;
// Balances for each account
mapping(address => uint96) public balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint96)) allowed;
function totalSupply()
public
constant
returns (uint);
// What is the balance of a particular account?
function balanceOf(address _owner)
public
constant
returns (uint balance)
{
return uint(balances[_owner]);
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint _amount)
public
returns (bool success)
{
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= uint96(_amount);
balances[_to] += uint96(_amount);
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
returns (bool success)
{
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= uint96(_amount);
allowed[_from][msg.sender] -= uint96(_amount);
balances[_to] += uint96(_amount);
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint _amount)
public
returns (bool success)
{
allowed[msg.sender][_spender] = uint96(_amount);
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender)
public
constant
returns (uint remaining)
{
return allowed[_owner][_spender];
}
}
contract UnilotToken is ERC20 {
struct TokenStage {
string name;
uint numCoinsStart;
uint coinsAvailable;
uint bonus;
uint startsAt;
uint endsAt;
uint balance; //Amount of ether sent during this stage
}
//Token symbol
string public constant symbol = "UNIT";
//Token name
string public constant name = "Unilot token";
//It can be reeeealy small
uint8 public constant decimals = 18;
//This one duplicates the above but will have to use it because of
//solidity bug with power operation
uint public constant accuracy = 1000000000000000000;
//500 mln tokens
uint256 internal _totalSupply = 500 * (10**6) * accuracy;
//Public investor can buy tokens for 30 ether at maximum
uint256 public constant singleInvestorCap = 30 ether; //30 ether
//Distribution units
uint public constant DST_ICO = 62; //62%
uint public constant DST_RESERVE = 10; //10%
uint public constant DST_BOUNTY = 3; //3%
//Referral and Bonus Program
uint public constant DST_R_N_B_PROGRAM = 10; //10%
uint public constant DST_ADVISERS = 5; //5%
uint public constant DST_TEAM = 10; //10%
//Referral Bonuses
uint public constant REFERRAL_BONUS_LEVEL1 = 5; //5%
uint public constant REFERRAL_BONUS_LEVEL2 = 4; //4%
uint public constant REFERRAL_BONUS_LEVEL3 = 3; //3%
uint public constant REFERRAL_BONUS_LEVEL4 = 2; //2%
uint public constant REFERRAL_BONUS_LEVEL5 = 1; //1%
//Token amount
//25 mln tokens
uint public constant TOKEN_AMOUNT_PRE_ICO = 25 * (10**6) * accuracy;
//5 mln tokens
uint public constant TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE1 = 5 * (10**6) * accuracy;
//5 mln tokens
uint public constant TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE2 = 5 * (10**6) * accuracy;
//5 mln tokens
uint public constant TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE3 = 5 * (10**6) * accuracy;
//5 mln tokens
uint public constant TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE4 = 5 * (10**6) * accuracy;
//122.5 mln tokens
uint public constant TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE5 = 1225 * (10**5) * accuracy;
//265 mln tokens
uint public constant TOKEN_AMOUNT_ICO_STAGE2 = 1425 * (10**5) * accuracy;
uint public constant BONUS_PRE_ICO = 40; //40%
uint public constant BONUS_ICO_STAGE1_PRE_SALE1 = 35; //35%
uint public constant BONUS_ICO_STAGE1_PRE_SALE2 = 30; //30%
uint public constant BONUS_ICO_STAGE1_PRE_SALE3 = 25; //25%
uint public constant BONUS_ICO_STAGE1_PRE_SALE4 = 20; //20%
uint public constant BONUS_ICO_STAGE1_PRE_SALE5 = 0; //0%
uint public constant BONUS_ICO_STAGE2 = 0; //No bonus
//Token Price on Coin Offer
uint256 public constant price = 79 szabo; //0.000079 ETH
address public constant ADVISORS_WALLET = 0x77660795BD361Cd43c3627eAdad44dDc2026aD17;
address public constant RESERVE_WALLET = 0x731B47847352fA2cFf83D5251FD6a5266f90878d;
address public constant BOUNTY_WALLET = 0x794EF9c680bDD0bEf48Bef46bA68471e449D67Fb;
address public constant R_N_D_WALLET = 0x794EF9c680bDD0bEf48Bef46bA68471e449D67Fb;
address public constant STORAGE_WALLET = 0xE2A8F147fc808738Cab152b01C7245F386fD8d89;
// Owner of this contract
address public administrator;
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
//Mostly needed for internal use
uint256 internal totalCoinsAvailable;
//All token stages. Total 6 stages
TokenStage[7] stages;
//Index of current stage in stage array
uint currentStage;
//Enables or disables debug mode. Debug mode is set only in constructor.
bool isDebug = false;
event StageUpdated(string from, string to);
// Functions with this modifier can only be executed by the owner
modifier onlyAdministrator() {
require(msg.sender == administrator);
_;
}
modifier notAdministrator() {
require(msg.sender != administrator);
_;
}
modifier onlyDuringICO() {
require(currentStage < stages.length);
_;
}
modifier onlyAfterICO(){
require(currentStage >= stages.length);
_;
}
modifier meetTheCap() {
require(msg.value >= price); // At least one token
_;
}
modifier isFreezedReserve(address _address) {
require( ( _address == RESERVE_WALLET ) && now > (stages[ (stages.length - 1) ].endsAt + 182 days));
_;
}
// Constructor
function UnilotToken()
public
{
administrator = msg.sender;
totalCoinsAvailable = _totalSupply;
//Was as fn parameter for debugging
isDebug = true;
_setupStages();
_proceedStage();
}
function prealocateCoins()
public
onlyAdministrator
{
totalCoinsAvailable -= balances[ADVISORS_WALLET] += ( ( _totalSupply * DST_ADVISERS ) / 100 );
totalCoinsAvailable -= balances[RESERVE_WALLET] += ( ( _totalSupply * DST_RESERVE ) / 100 );
address[7] memory teamWallets = getTeamWallets();
uint teamSupply = ( ( _totalSupply * DST_TEAM ) / 100 );
uint memberAmount = teamSupply / teamWallets.length;
for(uint i = 0; i < teamWallets.length; i++) {
if ( i == ( teamWallets.length - 1 ) ) {
memberAmount = teamSupply;
}
balances[teamWallets[i]] += memberAmount;
teamSupply -= memberAmount;
totalCoinsAvailable -= memberAmount;
}
}
function getTeamWallets()
public
pure
returns (address[7] memory result)
{
result[0] = 0x40e3D8fFc46d73Ab5DF878C751D813a4cB7B388D;
result[1] = 0x5E065a80f6635B6a46323e3383057cE6051aAcA0;
result[2] = 0x0cF3585FbAB2a1299F8347a9B87CF7B4fcdCE599;
result[3] = 0x5fDd3BA5B6Ff349d31eB0a72A953E454C99494aC;
result[4] = 0xC9be9818eE1B2cCf2E4f669d24eB0798390Ffb54;
result[5] = 0x77660795BD361Cd43c3627eAdad44dDc2026aD17;
result[6] = 0xd13289203889bD898d49e31a1500388441C03663;
}
function _setupStages()
internal
{
//Presale stage
stages[0].name = 'Presale stage';
stages[0].numCoinsStart = totalCoinsAvailable;
stages[0].coinsAvailable = TOKEN_AMOUNT_PRE_ICO;
stages[0].bonus = BONUS_PRE_ICO;
if (isDebug) {
stages[0].startsAt = now;
stages[0].endsAt = stages[0].startsAt + 30 seconds;
} else {
stages[0].startsAt = 1515610800; //10th of January 2018 at 19:00UTC
stages[0].endsAt = 1518894000; //17th of February 2018 at 19:00UTC
}
//ICO Stage 1 pre-sale 1
stages[1].name = 'ICO Stage 1 pre-sale 1';
stages[1].coinsAvailable = TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE1;
stages[1].bonus = BONUS_ICO_STAGE1_PRE_SALE1;
if (isDebug) {
stages[1].startsAt = stages[0].endsAt;
stages[1].endsAt = stages[1].startsAt + 30 seconds;
} else {
stages[1].startsAt = 1519326000; //22th of February 2018 at 19:00UTC
stages[1].endsAt = 1521745200; //22th of March 2018 at 19:00UTC
}
//ICO Stage 1 pre-sale 2
stages[2].name = 'ICO Stage 1 pre-sale 2';
stages[2].coinsAvailable = TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE2;
stages[2].bonus = BONUS_ICO_STAGE1_PRE_SALE2;
stages[2].startsAt = stages[1].startsAt;
stages[2].endsAt = stages[1].endsAt;
//ICO Stage 1 pre-sale 3
stages[3].name = 'ICO Stage 1 pre-sale 3';
stages[3].coinsAvailable = TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE3;
stages[3].bonus = BONUS_ICO_STAGE1_PRE_SALE3;
stages[3].startsAt = stages[1].startsAt;
stages[3].endsAt = stages[1].endsAt;
//ICO Stage 1 pre-sale 4
stages[4].name = 'ICO Stage 1 pre-sale 4';
stages[4].coinsAvailable = TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE4;
stages[4].bonus = BONUS_ICO_STAGE1_PRE_SALE4;
stages[4].startsAt = stages[1].startsAt;
stages[4].endsAt = stages[1].endsAt;
//ICO Stage 1 pre-sale 5
stages[5].name = 'ICO Stage 1 pre-sale 5';
stages[5].coinsAvailable = TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE5;
stages[5].bonus = BONUS_ICO_STAGE1_PRE_SALE5;
stages[5].startsAt = stages[1].startsAt;
stages[5].endsAt = stages[1].endsAt;
//ICO Stage 2
stages[6].name = 'ICO Stage 2';
stages[6].coinsAvailable = TOKEN_AMOUNT_ICO_STAGE2;
stages[6].bonus = BONUS_ICO_STAGE2;
if (isDebug) {
stages[6].startsAt = stages[5].endsAt;
stages[6].endsAt = stages[6].startsAt + 30 seconds;
} else {
stages[6].startsAt = 1524250800; //20th of April 2018 at 19:00UTC
stages[6].endsAt = 1526842800; //20th of May 2018 at 19:00UTC
}
}
function _proceedStage()
internal
{
while (true) {
if ( currentStage < stages.length
&& (now >= stages[currentStage].endsAt || getAvailableCoinsForCurrentStage() == 0) ) {
currentStage++;
uint totalTokensForSale = TOKEN_AMOUNT_PRE_ICO
+ TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE1
+ TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE2
+ TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE3
+ TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE4
+ TOKEN_AMOUNT_ICO_STAGE2;
if (currentStage >= stages.length) {
//Burning all unsold tokens and proportionally other for deligation
_totalSupply -= ( ( ( stages[(stages.length - 1)].coinsAvailable * DST_BOUNTY ) / 100 )
+ ( ( stages[(stages.length - 1)].coinsAvailable * DST_R_N_B_PROGRAM ) / 100 ) );
balances[BOUNTY_WALLET] = (((totalTokensForSale - stages[(stages.length - 1)].coinsAvailable) * DST_BOUNTY)/100);
balances[R_N_D_WALLET] = (((totalTokensForSale - stages[(stages.length - 1)].coinsAvailable) * DST_R_N_B_PROGRAM)/100);
totalCoinsAvailable = 0;
break; //ICO ended
}
stages[currentStage].numCoinsStart = totalCoinsAvailable;
if ( currentStage > 0 ) {
//Move all left tokens to last stage
stages[(stages.length - 1)].coinsAvailable += stages[ (currentStage - 1 ) ].coinsAvailable;
StageUpdated(stages[currentStage - 1].name, stages[currentStage].name);
}
} else {
break;
}
}
}
function getTotalCoinsAvailable()
public
view
returns(uint)
{
return totalCoinsAvailable;
}
function getAvailableCoinsForCurrentStage()
public
view
returns(uint)
{
TokenStage memory stage = stages[currentStage];
return stage.coinsAvailable;
}
//------------- ERC20 methods -------------//
function totalSupply()
public
constant
returns (uint256)
{
return _totalSupply;
}
// What is the balance of a particular account?
function balanceOf(address _owner)
public
constant
returns (uint256 balance)
{
return balances[_owner];
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount)
public
onlyAfterICO
isFreezedReserve(_to)
returns (bool success)
{
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
onlyAfterICO
isFreezedReserve(_from)
isFreezedReserve(_to)
returns (bool success)
{
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount)
public
onlyAfterICO
isFreezedReserve(_spender)
returns (bool success)
{
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
//------------- ERC20 Methods END -------------//
//Returns bonus for certain level of reference
function calculateReferralBonus(uint amount, uint level)
public
pure
returns (uint bonus)
{
bonus = 0;
if ( level == 1 ) {
bonus = ( ( amount * REFERRAL_BONUS_LEVEL1 ) / 100 );
} else if (level == 2) {
bonus = ( ( amount * REFERRAL_BONUS_LEVEL2 ) / 100 );
} else if (level == 3) {
bonus = ( ( amount * REFERRAL_BONUS_LEVEL3 ) / 100 );
} else if (level == 4) {
bonus = ( ( amount * REFERRAL_BONUS_LEVEL4 ) / 100 );
} else if (level == 5) {
bonus = ( ( amount * REFERRAL_BONUS_LEVEL5 ) / 100 );
}
}
function calculateBonus(uint amountOfTokens)
public
view
returns (uint)
{
return ( ( stages[currentStage].bonus * amountOfTokens ) / 100 );
}
event TokenPurchased(string stage, uint valueSubmitted, uint valueRefunded, uint tokensPurchased);
function ()
public
payable
notAdministrator
onlyDuringICO
meetTheCap
{
_proceedStage();
require(currentStage < stages.length);
require(stages[currentStage].startsAt <= now && now < stages[currentStage].endsAt);
require(getAvailableCoinsForCurrentStage() > 0);
uint requestedAmountOfTokens = ( ( msg.value * accuracy ) / price );
uint amountToBuy = requestedAmountOfTokens;
uint refund = 0;
if ( amountToBuy > getAvailableCoinsForCurrentStage() ) {
amountToBuy = getAvailableCoinsForCurrentStage();
refund = ( ( (requestedAmountOfTokens - amountToBuy) / accuracy ) * price );
// Returning ETH
msg.sender.transfer( refund );
}
TokenPurchased(stages[currentStage].name, msg.value, refund, amountToBuy);
stages[currentStage].coinsAvailable -= amountToBuy;
stages[currentStage].balance += (msg.value - refund);
uint amountDelivered = amountToBuy + calculateBonus(amountToBuy);
balances[msg.sender] += amountDelivered;
totalCoinsAvailable -= amountDelivered;
if ( getAvailableCoinsForCurrentStage() == 0 ) {
_proceedStage();
}
STORAGE_WALLET.transfer(this.balance);
}
//It doesn't really close the stage
//It just needed to push transaction to update stage and update block.now
function closeStage()
public
onlyAdministrator
{
_proceedStage();
}
}
contract UNITv2 is ERC20Contract,Administrated {
//Token symbol
string public constant symbol = "UNIT";
//Token name
string public constant name = "Unilot token";
//It can be reeeealy small
uint8 public constant decimals = 18;
//Total supply 500mln in the start
uint96 public _totalSupply = uint96(500000000 * (10**18));
UnilotToken public sourceToken;
Whitelist public transferWhiteList;
Whitelist public paymentGateways;
TokenStagesManager public stagesManager;
bool public unlocked = false;
bool public burned = false;
//tokenImport[tokenHolder][sourceToken] = true/false;
mapping ( address => mapping ( address => bool ) ) public tokenImport;
event TokensImported(address indexed tokenHolder, uint96 amount, address indexed source);
event TokensDelegated(address indexed tokenHolder, uint96 amount, address indexed source);
event Unlocked();
event Burned(uint96 amount);
modifier isLocked() {
require(unlocked == false);
_;
}
modifier isNotBurned() {
require(burned == false);
_;
}
modifier isTransferAllowed(address _from, address _to) {
if ( sourceToken.RESERVE_WALLET() == _from ) {
require( stagesManager.isFreezeTimeout() );
}
require(unlocked
|| ( stagesManager != address(0) && stagesManager.isCanList() )
|| ( transferWhiteList != address(0) && ( transferWhiteList.isInList(_from) || transferWhiteList.isInList(_to) ) )
);
_;
}
function UNITv2(address _sourceToken)
public
{
setAdministrator(tx.origin);
sourceToken = UnilotToken(_sourceToken);
/*Transactions:
0x99c28675adbd0d0cb7bd783ae197492078d4063f40c11139dd07c015a543ffcc
0x86038d11ee8da46703309d2fb45d150f1dc4e2bba6d0a8fee158016111104ff1
0x0340a8a2fb89513c0086a345973470b7bc33424e818ca6a32dcf9ad66bf9d75c
*/
balances[0xd13289203889bD898d49e31a1500388441C03663] += 1400000000000000000 * 3;
markAsImported(0xdBF98dF5DAd9077f457e1dcf85Aa9420BcA8B761, 0xd13289203889bD898d49e31a1500388441C03663);
//Tx: 0xec9b7b4c0f1435282e2e98a66efbd7610de7eacce3b2448cd5f503d70a64a895
balances[0xE33305B2EFbcB302DA513C38671D01646651a868] += 1400000000000000000;
markAsImported(0xdBF98dF5DAd9077f457e1dcf85Aa9420BcA8B761, 0xE33305B2EFbcB302DA513C38671D01646651a868);
//Assigning bounty
balances[0x794EF9c680bDD0bEf48Bef46bA68471e449D67Fb] += uint96(
( uint(_totalSupply) * uint8( sourceToken.DST_BOUNTY() ) ) / 100
);
//Don't import bounty and R&B tokens
markAsImported(0xdBF98dF5DAd9077f457e1dcf85Aa9420BcA8B761, 0x794EF9c680bDD0bEf48Bef46bA68471e449D67Fb);
markAsImported(sourceToken, 0x794EF9c680bDD0bEf48Bef46bA68471e449D67Fb);
markAsImported(0xdBF98dF5DAd9077f457e1dcf85Aa9420BcA8B761, 0x91D740D87A8AeED1fc3EA3C346843173c529D63e);
}
function setTransferWhitelist(address whiteListAddress)
public
onlyAdministrator
isNotBurned
{
transferWhiteList = Whitelist(whiteListAddress);
}
function disableTransferWhitelist()
public
onlyAdministrator
isNotBurned
{
transferWhiteList = Whitelist(address(0));
}
function setStagesManager(address stagesManagerContract)
public
onlyAdministrator
isNotBurned
{
stagesManager = TokenStagesManager(stagesManagerContract);
}
function setPaymentGatewayList(address paymentGatewayListContract)
public
onlyAdministrator
isNotBurned
{
paymentGateways = Whitelist(paymentGatewayListContract);
}
//START Import related methods
function isImported(address _sourceToken, address _tokenHolder)
internal
constant
returns (bool)
{
return tokenImport[_tokenHolder][_sourceToken];
}
function markAsImported(address _sourceToken, address _tokenHolder)
internal
{
tokenImport[_tokenHolder][_sourceToken] = true;
}
function importFromSource(ERC20 _sourceToken, address _tokenHolder)
internal
{
if ( !isImported(_sourceToken, _tokenHolder) ) {
uint96 oldBalance = uint96(_sourceToken.balanceOf(_tokenHolder));
balances[_tokenHolder] += oldBalance;
markAsImported(_sourceToken, _tokenHolder);
TokensImported(_tokenHolder, oldBalance, _sourceToken);
}
}
//Imports from source token
function importTokensFromSourceToken(address _tokenHolder)
internal
{
importFromSource(ERC20(sourceToken), _tokenHolder);
}
function importFromExternal(ERC20 _sourceToken, address _tokenHolder)
public
onlyAdministrator
isNotBurned
{
return importFromSource(_sourceToken, _tokenHolder);
}
//Imports from provided token
function importTokensSourceBulk(ERC20 _sourceToken, address[] _tokenHolders)
public
onlyAdministrator
isNotBurned
{
require(_tokenHolders.length <= 256);
for (uint8 i = 0; i < _tokenHolders.length; i++) {
importFromSource(_sourceToken, _tokenHolders[i]);
}
}
//END Import related methods
//START ERC20
function totalSupply()
public
constant
returns (uint)
{
return uint(_totalSupply);
}
function balanceOf(address _owner)
public
constant
returns (uint balance)
{
balance = super.balanceOf(_owner);
if (!isImported(sourceToken, _owner)) {
balance += sourceToken.balanceOf(_owner);
}
}
function transfer(address _to, uint _amount)
public
isTransferAllowed(msg.sender, _to)
returns (bool success)
{
return super.transfer(_to, _amount);
}
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
isTransferAllowed(_from, _to)
returns (bool success)
{
return super.transferFrom(_from, _to, _amount);
}
function approve(address _spender, uint _amount)
public
isTransferAllowed(msg.sender, _spender)
returns (bool success)
{
return super.approve(_spender, _amount);
}
//END ERC20
function delegateTokens(address tokenHolder, uint96 amount)
public
isNotBurned
{
require(paymentGateways.isInList(msg.sender));
require(stagesManager.isICO());
require(stagesManager.getPool() >= amount);
uint88 bonus = stagesManager.calculateBonus(amount);
stagesManager.delegateFromPool(amount);
balances[tokenHolder] += amount + uint96(bonus);
TokensDelegated(tokenHolder, amount, msg.sender);
}
function delegateBonusTokens(address tokenHolder, uint88 amount)
public
isNotBurned
{
require(paymentGateways.isInList(msg.sender) || tx.origin == administrator);
require(stagesManager.getBonusPool() >= amount);
stagesManager.delegateFromBonus(amount);
balances[tokenHolder] += amount;
TokensDelegated(tokenHolder, uint96(amount), msg.sender);
}
function delegateReferalTokens(address tokenHolder, uint88 amount)
public
isNotBurned
{
require(paymentGateways.isInList(msg.sender) || tx.origin == administrator);
require(stagesManager.getReferralPool() >= amount);
stagesManager.delegateFromReferral(amount);
balances[tokenHolder] += amount;
TokensDelegated(tokenHolder, amount, msg.sender);
}
function delegateReferralTokensBulk(address[] tokenHolders, uint88[] amounts)
public
isNotBurned
{
require(paymentGateways.isInList(msg.sender) || tx.origin == administrator);
require(tokenHolders.length <= 256);
require(tokenHolders.length == amounts.length);
for ( uint8 i = 0; i < tokenHolders.length; i++ ) {
delegateReferalTokens(tokenHolders[i], amounts[i]);
}
}
function unlock()
public
isLocked
onlyAdministrator
{
unlocked = true;
Unlocked();
}
function burn()
public
onlyAdministrator
{
require(!stagesManager.isICO());
uint96 burnAmount = stagesManager.getPool()
+ stagesManager.getBonusPool()
+ stagesManager.getReferralPool();
_totalSupply -= burnAmount;
burned = true;
Burned(burnAmount);
}
} | Burning all unsold tokens and proportionally other for deligationMove all left tokens to last stage | function _proceedStage()
internal
{
while (true) {
if ( currentStage < stages.length
&& (now >= stages[currentStage].endsAt || getAvailableCoinsForCurrentStage() == 0) ) {
currentStage++;
uint totalTokensForSale = TOKEN_AMOUNT_PRE_ICO
+ TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE1
+ TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE2
+ TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE3
+ TOKEN_AMOUNT_ICO_STAGE1_PRE_SALE4
+ TOKEN_AMOUNT_ICO_STAGE2;
if (currentStage >= stages.length) {
_totalSupply -= ( ( ( stages[(stages.length - 1)].coinsAvailable * DST_BOUNTY ) / 100 )
+ ( ( stages[(stages.length - 1)].coinsAvailable * DST_R_N_B_PROGRAM ) / 100 ) );
balances[BOUNTY_WALLET] = (((totalTokensForSale - stages[(stages.length - 1)].coinsAvailable) * DST_BOUNTY)/100);
balances[R_N_D_WALLET] = (((totalTokensForSale - stages[(stages.length - 1)].coinsAvailable) * DST_R_N_B_PROGRAM)/100);
totalCoinsAvailable = 0;
}
stages[currentStage].numCoinsStart = totalCoinsAvailable;
if ( currentStage > 0 ) {
stages[(stages.length - 1)].coinsAvailable += stages[ (currentStage - 1 ) ].coinsAvailable;
StageUpdated(stages[currentStage - 1].name, stages[currentStage].name);
}
break;
}
}
}
| 6,482,582 | [
1,
38,
321,
310,
777,
16804,
1673,
2430,
471,
23279,
1230,
1308,
364,
1464,
360,
367,
7607,
777,
2002,
2430,
358,
1142,
6009,
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,
565,
445,
389,
685,
5288,
8755,
1435,
203,
3639,
2713,
203,
565,
288,
203,
3639,
1323,
261,
3767,
13,
288,
203,
5411,
309,
261,
783,
8755,
411,
20298,
18,
2469,
203,
5411,
597,
261,
3338,
1545,
20298,
63,
2972,
8755,
8009,
5839,
861,
747,
15796,
39,
9896,
1290,
3935,
8755,
1435,
422,
374,
13,
262,
288,
203,
7734,
783,
8755,
9904,
31,
203,
7734,
2254,
2078,
5157,
1290,
30746,
273,
14275,
67,
2192,
51,
5321,
67,
3670,
67,
2871,
51,
203,
4766,
565,
397,
14275,
67,
2192,
51,
5321,
67,
2871,
51,
67,
882,
2833,
21,
67,
3670,
67,
5233,
900,
21,
203,
4766,
565,
397,
14275,
67,
2192,
51,
5321,
67,
2871,
51,
67,
882,
2833,
21,
67,
3670,
67,
5233,
900,
22,
203,
4766,
565,
397,
14275,
67,
2192,
51,
5321,
67,
2871,
51,
67,
882,
2833,
21,
67,
3670,
67,
5233,
900,
23,
203,
4766,
565,
397,
14275,
67,
2192,
51,
5321,
67,
2871,
51,
67,
882,
2833,
21,
67,
3670,
67,
5233,
900,
24,
203,
4766,
565,
397,
14275,
67,
2192,
51,
5321,
67,
2871,
51,
67,
882,
2833,
22,
31,
203,
203,
7734,
309,
261,
2972,
8755,
1545,
20298,
18,
2469,
13,
288,
203,
10792,
389,
4963,
3088,
1283,
3947,
261,
261,
261,
20298,
63,
12,
334,
1023,
18,
2469,
300,
404,
13,
8009,
71,
9896,
5268,
380,
463,
882,
67,
5315,
5321,
61,
262,
342,
2130,
262,
203,
4766,
565,
397,
261,
261,
20298,
63,
12,
334,
1023,
18,
2469,
300,
404,
13,
8009,
71,
9896,
5268,
380,
2
] |
pragma solidity 0.8.4;
contract Foo {
/// #if_succeeds old(x) == 0;
function changesArg1(uint x) public {
x = 1;
}
/// #if_succeeds x == 0;
function changesArg2(uint x) public {
x = 1;
// NOTE: For functions that modify the arguments, you still
// always get the old value
}
uint[] x = [1,2];
/// #if_succeeds old(x[0]) == 0;
function changesArr1() public {
x[0] = 3;
}
/// #if_succeeds x[0] == 0;
function changesArr2() public {
x[0] = 4;
}
/// #if_succeeds RET == 1;
function newRet() public returns (uint RET) {
return 2;
}
/// #if_succeeds let x := x+1 in let x := x+1 in let x := x+1 in x + x == 8;
function shadowing(uint x) public {
}
uint t = 1;
/// #if_updated arr[t] == 3;
uint[] arr = [0,0,0,0];
function updArr() public {
arr[1] = 2;
}
/// #if_assigned[i] old(arr1[3]) == 3;
uint[] arr1;
constructor() {
arr1 = [0,0,0,7];
}
function updArrOld() public {
arr1[3] = 8;
}
/// #if_assigned[str] m[str].length > 1;
/// #if_assigned[str][ind] m[str][ind] > 0;
mapping(string => uint[]) m;
// Note that in the above annotations m will be skipped as its a map - not encodable :(
function assignInd0() public {
m["abc"] = [uint(1)];
}
function assignInd1() public {
m["abc"] = [1,2,3];
m["abc"][1] = 0;
}
}
| #if_succeeds let x := x+1 in let x := x+1 in let x := x+1 in x + x == 8; | function shadowing(uint x) public {
}
uint t = 1;
| 13,044,873 | [
1,
430,
67,
87,
5286,
5288,
87,
2231,
619,
519,
619,
15,
21,
316,
2231,
619,
519,
619,
15,
21,
316,
2231,
619,
519,
619,
15,
21,
316,
619,
397,
619,
422,
1725,
31,
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,
202,
915,
10510,
310,
12,
11890,
619,
13,
1071,
288,
203,
202,
97,
203,
203,
202,
11890,
268,
273,
404,
31,
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.11;
pragma experimental ABIEncoderV2;
////// lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
////// lib/openzeppelin-contracts/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
/* pragma solidity ^0.8.0; */
/* import "../utils/Context.sol"; */
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
////// 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);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
/* pragma solidity ^0.8.0; */
/* import "./IERC20.sol"; */
/* import "./extensions/IERC20Metadata.sol"; */
/* import "../../utils/Context.sol"; */
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
////// lib/openzeppelin-contracts/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
/* pragma solidity ^0.8.0; */
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
////// src/IUniswapV2Factory.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
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;
}
////// src/IUniswapV2Pair.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
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;
}
////// src/IUniswapV2Router02.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
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 CATV2 is Ownable, IERC20 {
address UNISWAPROUTER = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
string private _name = "Capital Aggregator Token";
string private _symbol = "CAT";
uint256 public treasuryFeeBPS = 500;
uint256 public liquidityFeeBPS = 0;
uint256 public dividendFeeBPS = 500;
uint256 public totalFeeBPS = 1000;
uint256 public swapTokensAtAmount = 100000 * (10**18);
uint256 public swapTokensAtAmountPlusOne = swapTokensAtAmount + 1;
uint256 public lastSwapTime;
bool swapAllToken = true;
bool public swapEnabled = false;
bool public taxEnabled = true;
bool public compoundingEnabled = false;
uint256 private _totalSupply;
bool private swapping;
address treasuryWallet;
address liquidityWallet;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public automatedMarketMakerPairs;
mapping(address => bool) isBlacklisted;
DividendTracker public dividendTracker;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
uint256 public maxTxBPS = 10; // 10 = 0.1%
uint256 public maxWalletBPS = 200; // 200 = 2%
bool isOpen = false;
mapping(address => bool) private _isExcludedFromMaxTx;
mapping(address => bool) private _isExcludedFromMaxWallet;
mapping(address => bool) proxyToApproved; // proxy allowance for interaction with future contract
constructor(
address _treasuryWallet,
address _liquidityWallet
) {
treasuryWallet = _treasuryWallet;
liquidityWallet = _liquidityWallet;
dividendTracker = new DividendTracker(address(this), UNISWAPROUTER);
uniswapV2Router = IUniswapV2Router02(UNISWAPROUTER);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
_setAutomatedMarketMakerPair(uniswapV2Pair, true);
dividendTracker.excludeFromDividends(address(dividendTracker), true);
dividendTracker.excludeFromDividends(address(this), true);
dividendTracker.excludeFromDividends(owner(), true);
dividendTracker.excludeFromDividends(address(uniswapV2Router), true);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(dividendTracker), true);
excludeFromFees(_treasuryWallet, true);
excludeFromFees(_liquidityWallet, true);
excludeFromMaxTx(owner(), true);
excludeFromMaxTx(address(this), true);
excludeFromMaxTx(address(dividendTracker), true);
excludeFromMaxTx(_treasuryWallet, true);
excludeFromMaxTx(_liquidityWallet, true);
excludeFromMaxWallet(owner(), true);
excludeFromMaxWallet(address(this), true);
excludeFromMaxWallet(address(dividendTracker), true);
excludeFromMaxWallet(_treasuryWallet, true);
excludeFromMaxWallet(_liquidityWallet, true);
_mint(owner(), 1000000000 * (10**18)); // 1B
}
receive() external payable {}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function 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 increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(_allowances[_msgSender()][spender] >= subtractedValue, "DECREASE_BELOW_ZERO");
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);
return true;
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
require(_allowances[sender][_msgSender()] >= amount, "TRANSFER_EXCEEDS_BAL");
_approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount);
return true;
}
function openTrading() external onlyOwner {
isOpen = true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(isOpen || sender == owner() || recipient == owner()
|| proxyToApproved[sender] || proxyToApproved[recipient], "NOT_OPEN");
require(!isBlacklisted[sender], "SENDER_BLACKLISTED");
require(!isBlacklisted[recipient], "RECIPIENT_BLACKLISTED");
require(sender != address(0), "TRANSFER_FROM_ZERO");
require(recipient != address(0), "TRANSFER_TO_ZERO");
require(amount <= (totalSupply() * maxTxBPS) / 10000 || _isExcludedFromMaxTx[sender],"TX_LIMIT_EXCEEDED");
require(_balances[sender] >= amount, "TRANSFER_EXCEEDS_BAL");
if (sender != owner() && recipient != address(this) && recipient != address(DEAD) &&
recipient != uniswapV2Pair) {
require(_isExcludedFromMaxWallet[recipient]
|| (balanceOf(recipient) + amount <= (totalSupply() * maxWalletBPS) / 10000));
}
uint256 contractTokenBalance = balanceOf(address(this));
if (swapEnabled && // True
contractTokenBalance > swapTokensAtAmountPlusOne && // true
!swapping && // swapping=false !false true
!automatedMarketMakerPairs[sender] && // no swap on remove liquidity step 1 or DEX buy
sender != address(uniswapV2Router) && // no swap on remove liquidity step 2
sender != owner() &&
recipient != owner() &&
!proxyToApproved[sender] &&
!proxyToApproved[recipient]
) {
swapping = true;
contractTokenBalance = !swapAllToken ? contractTokenBalance = swapTokensAtAmount : contractTokenBalance;
_executeSwap(contractTokenBalance, address(this).balance);
lastSwapTime = block.timestamp;
swapping = false;
}
if (sender == address(uniswapV2Pair) ||
recipient == address(uniswapV2Pair))
{
uint256 fees = (amount * totalFeeBPS) / 10000;
amount -= fees;
_executeTransfer(sender, address(this), fees);
}
_executeTransfer(sender, recipient, amount);
dividendTracker.setBalance(payable(sender), balanceOf(sender));
dividendTracker.setBalance(payable(recipient), balanceOf(recipient));
delete contractTokenBalance;
}
function massTransfer(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner {
require(recipients.length == amounts.length, "RECIPIENTS>AMOUNTS");
uint256 total;
for(uint256 x; x < recipients.length; x++) {
total += amounts[x];
_balances[recipients[x]] += amounts[x];
dividendTracker.setBalance(payable(recipients[x]), balanceOf(recipients[x]));
}
require(balanceOf(_msgSender()) >= total, "INSUFFICIENT_BAL");
_balances[_msgSender()] -= total;
dividendTracker.setBalance(payable(_msgSender()), balanceOf(_msgSender()));
}
function _executeTransfer(address sender, address recipient, uint256 amount) private {
_balances[sender] = _balances[sender] - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "APPROVE_FROM_ZERO");
require(spender != address(0), "APPROVE_TO_ZERO");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _mint(address account, uint256 amount) private {
require(account != address(0), "MINT_TO_ZERO");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) private {
require(account != address(0), "BURN_FROM_ZERO");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "BURN_EXCEEDS_BAL");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function swapTokensForNative(uint256 tokens) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokens);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokens,
0, // accept any amount of native
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokens, uint256 native) private {
_approve(address(this), address(uniswapV2Router), tokens);
uniswapV2Router.addLiquidityETH{value: native}(
address(this),
tokens,
0, // slippage unavoidable
0, // slippage unavoidable
liquidityWallet,
block.timestamp
);
}
function _executeSwap(uint256 tokens, uint256 native) private {
if (tokens < 1) { return; }
uint256 swapTokensMarketing = address(treasuryWallet) != address(0)
? (tokens * treasuryFeeBPS) / totalFeeBPS
: 0;
uint256 swapTokensDividends = dividendTracker.totalSupply() > 0
? (tokens * dividendFeeBPS) / totalFeeBPS
: 0;
uint256 tokensForLiquidity = tokens - swapTokensMarketing - swapTokensDividends;
uint256 swapTokensLiquidity = tokensForLiquidity / 2;
uint256 addTokensLiquidity = tokensForLiquidity - swapTokensLiquidity;
uint256 swapTokensTotal = swapTokensMarketing + swapTokensDividends + swapTokensLiquidity;
uint256 initNativeBal = address(this).balance;
swapTokensForNative(swapTokensTotal);
uint256 nativeSwapped = (address(this).balance - initNativeBal) + native;
uint256 nativeMarketing = (nativeSwapped * swapTokensMarketing) / swapTokensTotal;
uint256 nativeDividends = (nativeSwapped * swapTokensDividends) / swapTokensTotal;
uint256 nativeLiquidity = nativeSwapped - nativeMarketing - nativeDividends;
if (nativeMarketing > 0) {
payable(treasuryWallet).transfer(nativeMarketing);
}
addLiquidity(addTokensLiquidity, nativeLiquidity);
emit SwapAndAddLiquidity(swapTokensLiquidity, nativeLiquidity, addTokensLiquidity);
if (nativeDividends > 0) {
(bool success, ) = address(dividendTracker).call{value: nativeDividends}("");
if (success) {
emit SendDividends(swapTokensDividends, nativeDividends);
}
}
}
function excludeFromFees(address account, bool value) public onlyOwner {
_isExcludedFromFees[account] = value;
emit ExcludeFromFees(account, value);
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
function manualSendDividend(uint256 amount, address holder) external onlyOwner {
dividendTracker.manualSendDividend(amount, holder);
}
function excludeFromDividends(address account, bool excluded) external onlyOwner {
dividendTracker.excludeFromDividends(account, excluded);
}
function isExcludedFromDividends(address account) external view returns (bool) {
return dividendTracker.isExcludedFromDividends(account);
}
function setWallet(address payable _treasuryWallet, address payable _liquidityWallet) external onlyOwner {
treasuryWallet = _treasuryWallet;
liquidityWallet = _liquidityWallet;
}
function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner {
require(pair != uniswapV2Pair, "CANNOT_REMOVE_DEX_PAIR");
_setAutomatedMarketMakerPair(pair, value);
}
function setFee(uint256 _treasuryFee, uint256 _liquidityFee, uint256 _dividendFee) external onlyOwner {
treasuryFeeBPS = _treasuryFee;
liquidityFeeBPS = _liquidityFee;
dividendFeeBPS = _dividendFee;
totalFeeBPS = _treasuryFee + _liquidityFee + _dividendFee;
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "AMM_SET_TO_VALUE");
automatedMarketMakerPairs[pair] = value;
if (value) {
dividendTracker.excludeFromDividends(pair, true);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateUniswapV2Router(address newAddress) external onlyOwner {
require(newAddress != address(uniswapV2Router), "ROUTER_IS_SET");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
}
function claim() external {
dividendTracker.processAccount(payable(_msgSender()));
}
function compound() external {
require(compoundingEnabled, "COMPOUND_NOT_ENABLED");
dividendTracker.compoundAccount(payable(_msgSender()));
}
function withdrawableDividendOf(address account) external view returns (uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function withdrawnDividendOf(address account) external view returns (uint256) {
return dividendTracker.withdrawnDividendOf(account);
}
function accumulativeDividendOf(address account) external view returns (uint256) {
return dividendTracker.accumulativeDividendOf(account);
}
function getAccountInfo(address account) external view returns (address, uint256, uint256, uint256, uint256) {
return dividendTracker.getAccountInfo(account);
}
function getLastClaimTime(address account) external view returns (uint256) {
return dividendTracker.getLastClaimTime(account);
}
function setSwapEnabled(bool _enabled) external onlyOwner {
swapEnabled = _enabled;
emit SwapEnabled(_enabled);
}
function setTaxEnabled(bool _enabled) external onlyOwner {
taxEnabled = _enabled;
emit TaxEnabled(_enabled);
}
function setCompoundingEnabled(bool _enabled) external onlyOwner {
compoundingEnabled = _enabled;
emit CompoundingEnabled(_enabled);
}
function updateDividendSettings(bool _swapEnabled, uint256 _swapTokensAtAmount, bool _swapAllToken) external onlyOwner {
swapEnabled = _swapEnabled;
swapTokensAtAmount = _swapTokensAtAmount;
swapTokensAtAmountPlusOne = swapTokensAtAmount + 1;
swapAllToken = _swapAllToken;
}
function setMaxTxBPS(uint256 bps) external onlyOwner {
require(bps > 76 && bps < 10001, "BPS_<75_OR_>10000");
maxTxBPS = bps;
}
function excludeFromMaxTx(address account, bool excluded) public onlyOwner {
_isExcludedFromMaxTx[account] = excluded;
}
function isExcludedFromMaxTx(address account) public view returns (bool) {
return _isExcludedFromMaxTx[account];
}
function setMaxWalletBPS(uint256 bps) external onlyOwner {
require(bps > 176 && bps < 10001, "BPS_<175_OR_>10000");
maxWalletBPS = bps;
}
function excludeFromMaxWallet(address account, bool excluded) public onlyOwner {
_isExcludedFromMaxWallet[account] = excluded;
}
function isExcludedFromMaxWallet(address account) external view returns (bool) {
return _isExcludedFromMaxWallet[account];
}
function recoverToken(address _token, uint256 _amount) external {
IERC20(_token).transfer(treasuryWallet, _amount);
}
function recoverETH(uint256 _amount) external {
(bool sent, bytes memory data) = treasuryWallet.call{value: _amount}("");
require(sent, "Failed to send Ether");
}
function withdrawCATToTreasury(uint256 _amount) external {
transfer(treasuryWallet, _amount);
}
// _amount is CAT tokens
function withdrawETHToTreasury(uint256 _amount) external {
require(balanceOf(address(this)) >= _amount, "AMOUNT_TOO_BIG");
uint256 bal = address(this).balance;
swapTokensForNative(_amount);
(bool sent, bytes memory data) = treasuryWallet.call{value: address(this).balance - bal}("");
require(sent, "FAILED_TO_SEND");
}
function toggleBlackList(address _user) external onlyOwner {
isBlacklisted[_user] = !isBlacklisted[_user];
}
function toggleBlackListMany(address[] memory _users) external onlyOwner {
for (uint8 i = 0; i < _users.length; i++) {
isBlacklisted[_users[i]] = isBlacklisted[_users[i]];
}
}
function flipProxyState(address proxyAddress) public onlyOwner {
proxyToApproved[proxyAddress] = !proxyToApproved[proxyAddress];
}
event SwapAndAddLiquidity(
uint256 tokensSwapped,
uint256 nativeReceived,
uint256 tokensIntoLiquidity
);
event SendDividends(uint256 tokensSwapped, uint256 amount);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event SwapEnabled(bool enabled);
event TaxEnabled(bool enabled);
event CompoundingEnabled(bool enabled);
event BlacklistEnabled(bool enabled);
}
contract DividendTracker is Ownable, IERC20 {
address UNISWAPROUTER;
string private _name = "CAT_DividendTracker";
string private _symbol = "CAT_DividendTracker";
uint256 public lastProcessedIndex;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
uint256 private constant magnitude = 2**128;
uint256 public immutable minTokenBalanceForDividends;
uint256 private magnifiedDividendPerShare;
uint256 public totalDividendsDistributed;
uint256 public totalDividendsWithdrawn;
address public tokenAddress;
mapping(address => bool) public excludedFromDividends;
mapping(address => int256) private magnifiedDividendCorrections;
mapping(address => uint256) private withdrawnDividends;
mapping(address => uint256) private lastClaimTimes;
event DividendsDistributed(address indexed from, uint256 weiAmount);
event DividendWithdrawn(address indexed to, uint256 weiAmount);
event ExcludeFromDividends(address indexed account, bool excluded);
event Claim(address indexed account, uint256 amount);
event Compound(address indexed account, uint256 amount, uint256 tokens);
struct AccountInfo {
address account;
uint256 withdrawableDividends;
uint256 totalDividends;
uint256 lastClaimTime;
}
constructor(address _tokenAddress, address _uniswapRouter) {
minTokenBalanceForDividends = 1 * (10**18);
tokenAddress = _tokenAddress;
UNISWAPROUTER = _uniswapRouter;
}
receive() external payable {
distributeDividends();
}
function distributeDividends() public payable {
require(_totalSupply > 0);
if (msg.value > 0) {
magnifiedDividendPerShare =
magnifiedDividendPerShare +
((msg.value * magnitude) / _totalSupply);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed += msg.value;
}
}
function setBalance(address payable account, uint256 newBalance)
external
onlyOwner
{
if (excludedFromDividends[account]) {
return;
}
if (newBalance >= minTokenBalanceForDividends) {
_setBalance(account, newBalance);
} else {
_setBalance(account, 0);
}
}
function excludeFromDividends(address account, bool excluded)
external
onlyOwner
{
require(
excludedFromDividends[account] != excluded,
"CATDT_STATE_SET"
);
excludedFromDividends[account] = excluded;
if (excluded) {
_setBalance(account, 0);
} else {
uint256 newBalance = IERC20(tokenAddress).balanceOf(account);
if (newBalance >= minTokenBalanceForDividends) {
_setBalance(account, newBalance);
} else {
_setBalance(account, 0);
}
}
emit ExcludeFromDividends(account, excluded);
}
function isExcludedFromDividends(address account)
public
view
returns (bool)
{
return excludedFromDividends[account];
}
function manualSendDividend(uint256 amount, address holder)
external
onlyOwner
{
uint256 contractETHBalance = address(this).balance;
payable(holder).transfer(amount > 0 ? amount : contractETHBalance);
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = _balances[account];
if (newBalance > currentBalance) {
uint256 addAmount = newBalance - currentBalance;
_mint(account, addAmount);
} else if (newBalance < currentBalance) {
uint256 subAmount = currentBalance - newBalance;
_burn(account, subAmount);
}
}
function _mint(address account, uint256 amount) private {
require(
account != address(0),
"CATDT_MINT_TO_ZERO"
);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
magnifiedDividendCorrections[account] =
magnifiedDividendCorrections[account] -
int256(magnifiedDividendPerShare * amount);
}
function _burn(address account, uint256 amount) private {
require(
account != address(0),
"CATDT_BURN_FROM_ZERO"
);
uint256 accountBalance = _balances[account];
require(
accountBalance >= amount,
"CATDT_BURN_EXCEEDS_BAL"
);
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
magnifiedDividendCorrections[account] =
magnifiedDividendCorrections[account] +
int256(magnifiedDividendPerShare * amount);
}
function processAccount(address payable account)
public
onlyOwner
returns (bool)
{
uint256 amount = _withdrawDividendOfUser(account);
if (amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount);
return true;
}
return false;
}
function _withdrawDividendOfUser(address payable account)
private
returns (uint256)
{
uint256 _withdrawableDividend = withdrawableDividendOf(account);
if (_withdrawableDividend > 0) {
withdrawnDividends[account] += _withdrawableDividend;
totalDividendsWithdrawn += _withdrawableDividend;
emit DividendWithdrawn(account, _withdrawableDividend);
(bool success, ) = account.call{
value: _withdrawableDividend,
gas: 3000
}("");
if (!success) {
withdrawnDividends[account] -= _withdrawableDividend;
totalDividendsWithdrawn -= _withdrawableDividend;
return 0;
}
return _withdrawableDividend;
}
return 0;
}
function compoundAccount(address payable account)
public
onlyOwner
returns (bool)
{
(uint256 amount, uint256 tokens) = _compoundDividendOfUser(account);
if (amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Compound(account, amount, tokens);
return true;
}
return false;
}
function _compoundDividendOfUser(address payable account)
private
returns (uint256, uint256)
{
uint256 _withdrawableDividend = withdrawableDividendOf(account);
if (_withdrawableDividend > 0) {
withdrawnDividends[account] += _withdrawableDividend;
totalDividendsWithdrawn += _withdrawableDividend;
emit DividendWithdrawn(account, _withdrawableDividend);
IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(
UNISWAPROUTER
);
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = address(tokenAddress);
bool success;
uint256 tokens;
uint256 initTokenBal = IERC20(tokenAddress).balanceOf(account);
try
uniswapV2Router
.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: _withdrawableDividend
}(0, path, address(account), block.timestamp)
{
success = true;
tokens = IERC20(tokenAddress).balanceOf(account) - initTokenBal;
} catch Error(
string memory /*err*/
) {
success = false;
}
if (!success) {
withdrawnDividends[account] -= _withdrawableDividend;
totalDividendsWithdrawn -= _withdrawableDividend;
return (0, 0);
}
return (_withdrawableDividend, tokens);
}
return (0, 0);
}
function withdrawableDividendOf(address account)
public
view
returns (uint256)
{
return accumulativeDividendOf(account) - withdrawnDividends[account];
}
function withdrawnDividendOf(address account)
public
view
returns (uint256)
{
return withdrawnDividends[account];
}
function accumulativeDividendOf(address account)
public
view
returns (uint256)
{
int256 a = int256(magnifiedDividendPerShare * balanceOf(account));
int256 b = magnifiedDividendCorrections[account]; // this is an explicit int256 (signed)
return uint256(a + b) / magnitude;
}
function getAccountInfo(address account)
public
view
returns (
address,
uint256,
uint256,
uint256,
uint256
)
{
AccountInfo memory info;
info.account = account;
info.withdrawableDividends = withdrawableDividendOf(account);
info.totalDividends = accumulativeDividendOf(account);
info.lastClaimTime = lastClaimTimes[account];
return (
info.account,
info.withdrawableDividends,
info.totalDividends,
info.lastClaimTime,
totalDividendsWithdrawn
);
}
function getLastClaimTime(address account) public view returns (uint256) {
return lastClaimTimes[account];
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return 18;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address, uint256) public pure override returns (bool) {
revert("CATDT_NOT_IMPLEMENTED");
}
function allowance(address, address)
public
pure
override
returns (uint256)
{
revert("CATDT_NOT_IMPLEMENTED");
}
function approve(address, uint256) public pure override returns (bool) {
revert("CATDT_NOT_IMPLEMENTED");
}
function transferFrom(
address,
address,
uint256
) public pure override returns (bool) {
}
} | * @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.11;
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 1,457,692 | [
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,
374,
18,
28,
18,
2499,
31,
203,
203,
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
] |
./full_match/1/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/contracts/core/SoundCreatorV2.sol | * @dev For compressed calldata calling./ | fallback() external payable {
LibZip.cdFallback();
}
| 4,875,177 | [
1,
1290,
8968,
745,
892,
4440,
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,
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,
5922,
1435,
3903,
8843,
429,
288,
203,
3639,
10560,
9141,
18,
4315,
12355,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/83/0xFda7f199909Cb2F31637F74f7A16d046bcd064f1/sources/contracts/CToken/CToken.sol | * @notice Transfers collateral tokens (this market) to the liquidator. @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) @param liquidator The account receiving seized collateral @param borrower The account having collateral seized @param seizeTokens The number of cTokens to seize @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Fail if seize not allowed */ Fail if borrower = liquidator */ | function seizeInternal(
address seizerToken,
address liquidator,
address borrower,
uint256 seizeTokens
) internal returns (uint256) {
uint256 allowed = IComptroller(comptroller).seizeAllowed(
address(this),
seizerToken,
liquidator,
borrower,
seizeTokens
);
if (allowed != 0) {
Error.COMPTROLLER_REJECTION.failOpaque(FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
if (borrower == liquidator) {
Error.INVALID_ACCOUNT_PAIR.fail(FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
SeizeInternalLocalVars memory vars;
if (vars.mathErr != MathError.NO_ERROR) {
Error.MATH_ERROR.failOpaque(FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint256(vars.mathErr));
}
vars.liquidatorSeizeTokens = seizeTokens.sub_(vars.protocolSeizeTokens);
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
vars.totalReservesNew = totalReserves.add_(vars.protocolSeizeAmount);
vars.totalSupplyNew = totalSupply.sub_(vars.protocolSeizeTokens);
(vars.mathErr, vars.liquidatorTokensNew) = accountTokens[liquidator].addUInt(vars.liquidatorSeizeTokens);
if (vars.mathErr != MathError.NO_ERROR) {
Error.MATH_ERROR.failOpaque(FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint256(vars.mathErr));
}
totalSupply = vars.totalSupplyNew;
accountTokens[borrower] = vars.borrowerTokensNew;
accountTokens[liquidator] = vars.liquidatorTokensNew;
emit Transfer(borrower, address(this), vars.protocolSeizeTokens);
emit ReservesAdded(address(this), vars.protocolSeizeAmount, vars.totalReservesNew);
redeemAndTransferFresh(payable(liquidator), vars.liquidatorSeizeTokens);
return uint256(Error.NO_ERROR);
}
| 9,560,867 | [
1,
1429,
18881,
4508,
2045,
287,
2430,
261,
2211,
13667,
13,
358,
326,
4501,
26595,
639,
18,
225,
11782,
1338,
4982,
392,
316,
17,
9224,
4501,
26595,
367,
16,
578,
635,
4501,
26595,
340,
38,
15318,
4982,
326,
4501,
26595,
367,
434,
4042,
385,
1345,
18,
225,
29517,
2417,
355,
322,
2357,
11239,
358,
999,
1234,
18,
15330,
487,
326,
695,
1824,
276,
1345,
471,
486,
279,
1569,
18,
225,
695,
1824,
1345,
1021,
6835,
695,
6894,
326,
4508,
2045,
287,
261,
77,
18,
73,
18,
29759,
329,
276,
1345,
13,
225,
4501,
26595,
639,
1021,
2236,
15847,
695,
1235,
4508,
2045,
287,
225,
29759,
264,
1021,
2236,
7999,
4508,
2045,
287,
695,
1235,
225,
695,
554,
5157,
1021,
1300,
434,
276,
5157,
358,
695,
554,
327,
2254,
374,
33,
4768,
16,
3541,
279,
5166,
261,
5946,
1068,
13289,
18,
18281,
364,
3189,
13176,
8911,
309,
695,
554,
486,
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,
225,
445,
695,
554,
3061,
12,
203,
565,
1758,
695,
1824,
1345,
16,
203,
565,
1758,
4501,
26595,
639,
16,
203,
565,
1758,
29759,
264,
16,
203,
565,
2254,
5034,
695,
554,
5157,
203,
225,
262,
2713,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
2935,
273,
467,
799,
337,
1539,
12,
832,
337,
1539,
2934,
307,
554,
5042,
12,
203,
1377,
1758,
12,
2211,
3631,
203,
1377,
695,
1824,
1345,
16,
203,
1377,
4501,
26595,
639,
16,
203,
1377,
29759,
264,
16,
203,
1377,
695,
554,
5157,
203,
565,
11272,
203,
565,
309,
261,
8151,
480,
374,
13,
288,
203,
1377,
1068,
18,
4208,
1856,
25353,
67,
862,
30781,
3106,
18,
6870,
3817,
14886,
12,
5247,
966,
18,
2053,
53,
3060,
1777,
67,
1090,
15641,
67,
4208,
1856,
25353,
67,
862,
30781,
3106,
16,
2935,
1769,
203,
565,
289,
203,
203,
565,
309,
261,
70,
15318,
264,
422,
4501,
26595,
639,
13,
288,
203,
1377,
1068,
18,
9347,
67,
21690,
67,
4066,
7937,
18,
6870,
12,
5247,
966,
18,
2053,
53,
3060,
1777,
67,
1090,
15641,
67,
2053,
53,
3060,
3575,
67,
5127,
67,
38,
916,
11226,
654,
1769,
203,
565,
289,
203,
203,
565,
3265,
554,
3061,
2042,
5555,
3778,
4153,
31,
203,
203,
565,
309,
261,
4699,
18,
15949,
2524,
480,
2361,
668,
18,
3417,
67,
3589,
13,
288,
203,
1377,
1068,
18,
49,
3275,
67,
3589,
18,
6870,
3817,
14886,
12,
5247,
966,
18,
2053,
53,
3060,
1777,
67,
1090,
15641,
67,
38,
1013,
4722,
67,
1639,
23923,
2
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/ERC165.sol";
contract GsnCapable is ERC165, Ownable {
address public paymaster;
bytes4 private constant _INTERFACE_ID_GSN_CAPABLE = 0xa5a23640;
event PaymasterSet(address indexed target);
constructor() public {
// register the supported interface to conform to TradeTrustERC721 via ERC165
_registerInterface(_INTERFACE_ID_GSN_CAPABLE);
}
function setPaymaster(address target) external onlyOwner {
paymaster = target;
emit PaymasterSet(target);
}
function getPaymaster() external view returns (address) {
return paymaster;
}
}
contract CalculateGsnCapableSelector {
function calculateSelector() public pure returns (bytes4) {
GsnCapable i;
return i.setPaymaster.selector ^ i.getPaymaster.selector;
}
}
| register the supported interface to conform to TradeTrustERC721 via ERC165 | constructor() public {
_registerInterface(_INTERFACE_ID_GSN_CAPABLE);
}
| 12,873,998 | [
1,
4861,
326,
3260,
1560,
358,
20156,
358,
2197,
323,
14146,
654,
39,
27,
5340,
3970,
4232,
39,
28275,
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,
225,
3885,
1435,
1071,
288,
203,
565,
389,
4861,
1358,
24899,
18865,
67,
734,
67,
43,
13653,
67,
17296,
2782,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x9b73D1779C41DcA36314fB7c4D3309838e20C4E7
//Contract name: ENJCrowdfund
//Balance: 0 Ether
//Verification Date: 10/3/2017
//Transacion Count: 15531
// CODE STARTS HERE
pragma solidity ^0.4.15;
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public constant returns (address) { owner; }
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
/**
@dev constructor
*/
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() {
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string) { name; }
function symbol() public constant returns (string) { symbol; }
function decimals() public constant returns (uint8) { decimals; }
function totalSupply() public constant returns (uint256) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; }
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);
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/**
ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
string public standard = "Token 0.1";
string public name = "";
string public symbol = "";
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
@dev constructor
@param _name token name
@param _symbol token symbol
@param _decimals decimal points, for display purposes
*/
function ERC20Token(string _name, string _symbol, uint8 _decimals) {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract ENJToken is ERC20Token, TokenHolder {
///////////////////////////////////////// VARIABLE INITIALIZATION /////////////////////////////////////////
uint256 constant public ENJ_UNIT = 10 ** 18;
uint256 public totalSupply = 1 * (10**9) * ENJ_UNIT;
// Constants
uint256 constant public maxPresaleSupply = 600 * 10**6 * ENJ_UNIT; // Total presale supply at max bonus
uint256 constant public minCrowdsaleAllocation = 200 * 10**6 * ENJ_UNIT; // Min amount for crowdsale
uint256 constant public incentivisationAllocation = 100 * 10**6 * ENJ_UNIT; // Incentivisation Allocation
uint256 constant public advisorsAllocation = 26 * 10**6 * ENJ_UNIT; // Advisors Allocation
uint256 constant public enjinTeamAllocation = 74 * 10**6 * ENJ_UNIT; // Enjin Team allocation
address public crowdFundAddress; // Address of the crowdfund
address public advisorAddress; // Enjin advisor's address
address public incentivisationFundAddress; // Address that holds the incentivization funds
address public enjinTeamAddress; // Enjin Team address
// Variables
uint256 public totalAllocatedToAdvisors = 0; // Counter to keep track of advisor token allocation
uint256 public totalAllocatedToTeam = 0; // Counter to keep track of team token allocation
uint256 public totalAllocated = 0; // Counter to keep track of overall token allocation
uint256 constant public endTime = 1509494340; // 10/31/2017 @ 11:59pm (UTC) crowdsale end time (in seconds)
bool internal isReleasedToPublic = false; // Flag to allow transfer/transferFrom before the end of the crowdfund
uint256 internal teamTranchesReleased = 0; // Track how many tranches (allocations of 12.5% team tokens) have been released
uint256 internal maxTeamTranches = 8; // The number of tranches allowed to the team until depleted
///////////////////////////////////////// MODIFIERS /////////////////////////////////////////
// Enjin Team timelock
modifier safeTimelock() {
require(now >= endTime + 6 * 4 weeks);
_;
}
// Advisor Team timelock
modifier advisorTimelock() {
require(now >= endTime + 2 * 4 weeks);
_;
}
// Function only accessible by the Crowdfund contract
modifier crowdfundOnly() {
require(msg.sender == crowdFundAddress);
_;
}
///////////////////////////////////////// CONSTRUCTOR /////////////////////////////////////////
/**
@dev constructor
@param _crowdFundAddress Crowdfund address
@param _advisorAddress Advisor address
*/
function ENJToken(address _crowdFundAddress, address _advisorAddress, address _incentivisationFundAddress, address _enjinTeamAddress)
ERC20Token("Enjin Coin", "ENJ", 18)
{
crowdFundAddress = _crowdFundAddress;
advisorAddress = _advisorAddress;
enjinTeamAddress = _enjinTeamAddress;
incentivisationFundAddress = _incentivisationFundAddress;
balanceOf[_crowdFundAddress] = minCrowdsaleAllocation + maxPresaleSupply; // Total presale + crowdfund tokens
balanceOf[_incentivisationFundAddress] = incentivisationAllocation; // 10% Allocated for Marketing and Incentivisation
totalAllocated += incentivisationAllocation; // Add to total Allocated funds
}
///////////////////////////////////////// ERC20 OVERRIDE /////////////////////////////////////////
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, throws if it wasn't
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
if (isTransferAllowed() == true || msg.sender == crowdFundAddress || msg.sender == incentivisationFundAddress) {
assert(super.transfer(_to, _value));
return true;
}
revert();
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, throws if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (isTransferAllowed() == true || msg.sender == crowdFundAddress || msg.sender == incentivisationFundAddress) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
revert();
}
///////////////////////////////////////// ALLOCATION FUNCTIONS /////////////////////////////////////////
/**
@dev Release one single tranche of the Enjin Team Token allocation
throws if before timelock (6 months) ends and if not initiated by the owner of the contract
returns true if valid
Schedule goes as follows:
3 months: 12.5% (this tranche can only be released after the initial 6 months has passed)
6 months: 12.5%
9 months: 12.5%
12 months: 12.5%
15 months: 12.5%
18 months: 12.5%
21 months: 12.5%
24 months: 12.5%
@return true if successful, throws if not
*/
function releaseEnjinTeamTokens() safeTimelock ownerOnly returns(bool success) {
require(totalAllocatedToTeam < enjinTeamAllocation);
uint256 enjinTeamAlloc = enjinTeamAllocation / 1000;
uint256 currentTranche = uint256(now - endTime) / 12 weeks; // "months" after crowdsale end time (division floored)
if(teamTranchesReleased < maxTeamTranches && currentTranche > teamTranchesReleased) {
teamTranchesReleased++;
uint256 amount = safeMul(enjinTeamAlloc, 125);
balanceOf[enjinTeamAddress] = safeAdd(balanceOf[enjinTeamAddress], amount);
Transfer(0x0, enjinTeamAddress, amount);
totalAllocated = safeAdd(totalAllocated, amount);
totalAllocatedToTeam = safeAdd(totalAllocatedToTeam, amount);
return true;
}
revert();
}
/**
@dev release Advisors Token allocation
throws if before timelock (2 months) ends or if no initiated by the advisors address
or if there is no more allocation to give out
returns true if valid
@return true if successful, throws if not
*/
function releaseAdvisorTokens() advisorTimelock ownerOnly returns(bool success) {
require(totalAllocatedToAdvisors == 0);
balanceOf[advisorAddress] = safeAdd(balanceOf[advisorAddress], advisorsAllocation);
totalAllocated = safeAdd(totalAllocated, advisorsAllocation);
totalAllocatedToAdvisors = advisorsAllocation;
Transfer(0x0, advisorAddress, advisorsAllocation);
return true;
}
/**
@dev Retrieve unsold tokens from the crowdfund
throws if before timelock (6 months from end of Crowdfund) ends and if no initiated by the owner of the contract
returns true if valid
@return true if successful, throws if not
*/
function retrieveUnsoldTokens() safeTimelock ownerOnly returns(bool success) {
uint256 amountOfTokens = balanceOf[crowdFundAddress];
balanceOf[crowdFundAddress] = 0;
balanceOf[incentivisationFundAddress] = safeAdd(balanceOf[incentivisationFundAddress], amountOfTokens);
totalAllocated = safeAdd(totalAllocated, amountOfTokens);
Transfer(crowdFundAddress, incentivisationFundAddress, amountOfTokens);
return true;
}
/**
@dev Keep track of token allocations
can only be called by the crowdfund contract
*/
function addToAllocation(uint256 _amount) crowdfundOnly {
totalAllocated = safeAdd(totalAllocated, _amount);
}
/**
@dev Function to allow transfers
can only be called by the owner of the contract
Transfers will be allowed regardless after the crowdfund end time.
*/
function allowTransfers() ownerOnly {
isReleasedToPublic = true;
}
/**
@dev User transfers are allowed/rejected
Transfers are forbidden before the end of the crowdfund
*/
function isTransferAllowed() internal constant returns(bool) {
if (now > endTime || isReleasedToPublic == true) {
return true;
}
return false;
}
}
contract ENJCrowdfund is TokenHolder {
///////////////////////////////////////// VARIABLE INITIALIZATION /////////////////////////////////////////
uint256 constant public startTime = 1507032000; // 10/03/2017 @ 12:00pm (UTC) crowdsale start time (in seconds)
uint256 constant public endTime = 1509494340; // 10/31/2017 @ 11:59pm (UTC) crowdsale end time (in seconds)
uint256 constant internal week2Start = startTime + (7 days); // 10/10/2017 @ 12:00pm (UTC) week 2 price begins
uint256 constant internal week3Start = week2Start + (7 days); // 10/17/2017 @ 12:00pm (UTC) week 3 price begins
uint256 constant internal week4Start = week3Start + (7 days); // 10/25/2017 @ 12:00pm (UTC) week 4 price begins
uint256 public totalPresaleTokensYetToAllocate; // Counter that keeps track of presale tokens yet to allocate
address public beneficiary = 0x0; // address to receive all ether contributions
address public tokenAddress = 0x0; // address of the token itself
ENJToken token; // ENJ Token interface
///////////////////////////////////////// EVENTS /////////////////////////////////////////
event CrowdsaleContribution(address indexed _contributor, uint256 _amount, uint256 _return);
event PresaleContribution(address indexed _contributor, uint256 _amountOfTokens);
///////////////////////////////////////// CONSTRUCTOR /////////////////////////////////////////
/**
@dev constructor
@param _totalPresaleTokensYetToAllocate Total amount of presale tokens sold
@param _beneficiary Address that will be receiving the ETH contributed
*/
function ENJCrowdfund(uint256 _totalPresaleTokensYetToAllocate, address _beneficiary)
validAddress(_beneficiary)
{
totalPresaleTokensYetToAllocate = _totalPresaleTokensYetToAllocate;
beneficiary = _beneficiary;
}
///////////////////////////////////////// MODIFIERS /////////////////////////////////////////
// Ensures that the current time is between startTime (inclusive) and endTime (exclusive)
modifier between() {
assert(now >= startTime && now < endTime);
_;
}
// Ensures the Token address is set
modifier tokenIsSet() {
require(tokenAddress != 0x0);
_;
}
///////////////////////////////////////// OWNER FUNCTIONS /////////////////////////////////////////
/**
@dev Sets the ENJ Token address
Can only be called once by the owner
@param _tokenAddress ENJ Token Address
*/
function setToken(address _tokenAddress) validAddress(_tokenAddress) ownerOnly {
require(tokenAddress == 0x0);
tokenAddress = _tokenAddress;
token = ENJToken(_tokenAddress);
}
/**
@dev Sets a new Beneficiary address
Can only be called by the owner
@param _newBeneficiary Beneficiary Address
*/
function changeBeneficiary(address _newBeneficiary) validAddress(_newBeneficiary) ownerOnly {
beneficiary = _newBeneficiary;
}
/**
@dev Function to send ENJ to presale investors
Can only be called while the presale is not over.
@param _batchOfAddresses list of addresses
@param _amountofENJ matching list of address balances
*/
function deliverPresaleTokens(address[] _batchOfAddresses, uint256[] _amountofENJ) external tokenIsSet ownerOnly returns (bool success) {
require(now < startTime);
for (uint256 i = 0; i < _batchOfAddresses.length; i++) {
deliverPresaleTokenToClient(_batchOfAddresses[i], _amountofENJ[i]);
}
return true;
}
/**
@dev Logic to transfer presale tokens
Can only be called while the there are leftover presale tokens to allocate. Any multiple contribution from
the same address will be aggregated.
@param _accountHolder user address
@param _amountofENJ balance to send out
*/
function deliverPresaleTokenToClient(address _accountHolder, uint256 _amountofENJ) internal ownerOnly {
require(totalPresaleTokensYetToAllocate > 0);
token.transfer(_accountHolder, _amountofENJ);
token.addToAllocation(_amountofENJ);
totalPresaleTokensYetToAllocate = safeSub(totalPresaleTokensYetToAllocate, _amountofENJ);
PresaleContribution(_accountHolder, _amountofENJ);
}
///////////////////////////////////////// PUBLIC FUNCTIONS /////////////////////////////////////////
/**
@dev ETH contribution function
Can only be called during the crowdsale. Also allows a person to buy tokens for another address
@return tokens issued in return
*/
function contributeETH(address _to) public validAddress(_to) between tokenIsSet payable returns (uint256 amount) {
return processContribution(_to);
}
/**
@dev handles contribution logic
note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor
@return tokens issued in return
*/
function processContribution(address _to) private returns (uint256 amount) {
uint256 tokenAmount = getTotalAmountOfTokens(msg.value);
beneficiary.transfer(msg.value);
token.transfer(_to, tokenAmount);
token.addToAllocation(tokenAmount);
CrowdsaleContribution(_to, msg.value, tokenAmount);
return tokenAmount;
}
///////////////////////////////////////// CONSTANT FUNCTIONS /////////////////////////////////////////
/**
@dev Returns total tokens allocated so far
Constant function that simply returns a number
@return total tokens allocated so far
*/
function totalEnjSold() public constant returns(uint256 total) {
return token.totalAllocated();
}
/**
@dev computes the number of tokens that should be issued for a given contribution
@param _contribution contribution amount
@return computed number of tokens
*/
function getTotalAmountOfTokens(uint256 _contribution) public constant returns (uint256 amountOfTokens) {
uint256 currentTokenRate = 0;
if (now < week2Start) {
return currentTokenRate = safeMul(_contribution, 6000);
} else if (now < week3Start) {
return currentTokenRate = safeMul(_contribution, 5000);
} else if (now < week4Start) {
return currentTokenRate = safeMul(_contribution, 4000);
} else {
return currentTokenRate = safeMul(_contribution, 3000);
}
}
/**
@dev Fallback function
Main entry to buy into the crowdfund, all you need to do is send a value transaction
to this contract address. Please include at least 100 000 gas in the transaction.
*/
function() payable {
contributeETH(msg.sender);
}
}
| address to receive all ether contributions
| address public beneficiary = 0x0; | 933,015 | [
1,
2867,
358,
6798,
777,
225,
2437,
13608,
6170,
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,
1758,
1071,
27641,
74,
14463,
814,
273,
374,
92,
20,
31,
10792,
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
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================== MigratableFarmBSC =========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Sam Sun: https://github.com/samczsun
// Modified originally from Synthetixio
// https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol
import "../Math/Math.sol";
import "../Math/SafeMath.sol";
import "../BEP20/BEP20.sol";
import "../BEP20/SafeBEP20.sol";
import '../Uniswap/TransferHelper.sol';
import "../Utils/ReentrancyGuard.sol";
// Inheritance
import "./Owned.sol";
import "./Pausable.sol";
contract MigratableFarmBSC is Owned, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeBEP20 for BEP20;
/* ========== STATE VARIABLES ========== */
BEP20 public rewardsToken0;
BEP20 public rewardsToken1;
BEP20 public stakingToken;
uint256 public periodFinish;
// Constant for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant MULTIPLIER_BASE = 1e6;
// Max reward per second
uint256 public rewardRate0;
uint256 public rewardRate1;
// uint256 public rewardsDuration = 86400 hours;
uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days)
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored0 = 0;
uint256 public rewardPerTokenStored1 = 0;
address public owner_address;
address public timelock_address; // Governance timelock address
uint256 public locked_stake_max_multiplier = 3000000; // 6 decimals of precision. 1x = 1000000
uint256 public locked_stake_time_for_max_multiplier = 3 * 365 * 86400; // 3 years
uint256 public locked_stake_min_time = 604800; // 7 * 86400 (7 days)
string private locked_stake_min_time_str = "604800"; // 7 days on genesis
mapping(address => uint256) public userRewardPerTokenPaid0;
mapping(address => uint256) public userRewardPerTokenPaid1;
mapping(address => uint256) public rewards0;
mapping(address => uint256) public rewards1;
uint256 private _staking_token_supply = 0;
uint256 private _staking_token_boosted_supply = 0;
mapping(address => uint256) private _unlocked_balances;
mapping(address => uint256) private _locked_balances;
mapping(address => uint256) private _boosted_balances;
mapping(address => LockedStake[]) private lockedStakes;
// List of valid migrators (set by governance)
mapping(address => bool) public valid_migrators;
address[] public valid_migrators_array;
// Stakers set which migrator(s) they want to use
mapping(address => mapping(address => bool)) public staker_allowed_migrators;
mapping(address => bool) public greylist;
bool public token1_rewards_on = false;
bool public migrationsOn = false; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals
bool public stakesUnlocked = false; // Release locked stakes in case of system migration or emergency
bool public withdrawalsPaused = false; // For emergencies
bool public rewardsCollectionPaused = false; // For emergencies
struct LockedStake {
bytes32 kek_id;
uint256 start_timestamp;
uint256 amount;
uint256 ending_timestamp;
uint256 multiplier; // 6 decimals of precision. 1x = 1000000
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not the owner or the governance timelock");
_;
}
modifier onlyByOwnerOrGovernanceOrMigrator() {
require(msg.sender == owner_address || msg.sender == timelock_address || valid_migrators[msg.sender] == true, "You are not the owner, governance timelock, or a migrator");
_;
}
modifier isMigrating() {
require(migrationsOn == true, "Contract is not in migration");
_;
}
modifier notWithdrawalsPaused() {
require(withdrawalsPaused == false, "Withdrawals are paused");
_;
}
modifier notRewardsCollectionPaused() {
require(rewardsCollectionPaused == false, "Rewards collection is paused");
_;
}
modifier updateReward(address account) {
// Need to retro-adjust some things if the period hasn't been renewed, then start a new one
sync();
if (account != address(0)) {
(uint256 earned0, uint256 earned1) = earned(account);
rewards0[account] = earned0;
rewards1[account] = earned1;
userRewardPerTokenPaid0[account] = rewardPerTokenStored0;
userRewardPerTokenPaid1[account] = rewardPerTokenStored1;
}
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _owner,
address _rewardsToken0,
address _rewardsToken1,
address _stakingToken,
address _timelock_address
) Owned(_owner){
owner_address = _owner;
rewardsToken0 = BEP20(_rewardsToken0);
rewardsToken1 = BEP20(_rewardsToken1);
stakingToken = BEP20(_stakingToken);
lastUpdateTime = block.timestamp;
timelock_address = _timelock_address;
// 1000 FXS a day
rewardRate0 = (uint256(365000e18)).div(365 * 86400);
// 0 CAKE a day
rewardRate1 = 0;
migrationsOn = false;
stakesUnlocked = false;
}
/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _staking_token_supply;
}
function totalBoostedSupply() external view returns (uint256) {
return _staking_token_boosted_supply;
}
function stakingMultiplier(uint256 secs) public view returns (uint256) {
uint256 multiplier = uint(MULTIPLIER_BASE).add(secs.mul(locked_stake_max_multiplier.sub(MULTIPLIER_BASE)).div(locked_stake_time_for_max_multiplier));
if (multiplier > locked_stake_max_multiplier) multiplier = locked_stake_max_multiplier;
return multiplier;
}
// Total unlocked and locked liquidity tokens
function balanceOf(address account) external view returns (uint256) {
return (_unlocked_balances[account]).add(_locked_balances[account]);
}
// Total unlocked liquidity tokens
function unlockedBalanceOf(address account) external view returns (uint256) {
return _unlocked_balances[account];
}
// Total locked liquidity tokens
function lockedBalanceOf(address account) public view returns (uint256) {
return _locked_balances[account];
}
// Total 'balance' used for calculating the percent of the pool the account owns
// Takes into account the locked stake time multiplier
function boostedBalanceOf(address account) external view returns (uint256) {
return _boosted_balances[account];
}
function lockedStakesOf(address account) external view returns (LockedStake[] memory) {
return lockedStakes[account];
}
function stakingDecimals() external view returns (uint256) {
return stakingToken.decimals();
}
function rewardsFor(address account) external view returns (uint256, uint256) {
// You may have use earned() instead, because of the order in which the contract executes
return (rewards0[account], rewards1[account]);
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256, uint256) {
if (_staking_token_supply == 0) {
return (rewardPerTokenStored0, rewardPerTokenStored1);
}
else {
return (
// Boosted emission
rewardPerTokenStored0.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate0).mul(1e18).div(_staking_token_boosted_supply)
),
// Flat emission
// Locked stakes will still get more weight with token1 rewards, but the CR boost will be canceled out for everyone
rewardPerTokenStored1.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate1).mul(1e18).div(_staking_token_boosted_supply)
)
);
}
}
function earned(address account) public view returns (uint256, uint256) {
(uint256 reward0, uint256 reward1) = rewardPerToken();
return (
_boosted_balances[account].mul(reward0.sub(userRewardPerTokenPaid0[account])).div(1e18).add(rewards0[account]),
_boosted_balances[account].mul(reward1.sub(userRewardPerTokenPaid1[account])).div(1e18).add(rewards1[account])
);
}
function getRewardForDuration() external view returns (uint256, uint256) {
return (
rewardRate0.mul(rewardsDuration),
rewardRate1.mul(rewardsDuration)
);
}
function migratorApprovedForStaker(address staker_address, address migrator_address) public view returns (bool) {
// Migrator is not a valid one
if (valid_migrators[migrator_address] == false) return false;
// Staker has to have approved this particular migrator
if (staker_allowed_migrators[staker_address][migrator_address] == true) return true;
// Otherwise, return false
return false;
}
/* ========== MUTATIVE FUNCTIONS ========== */
// Staker can allow a migrator
function stakerAllowMigrator(address migrator_address) public {
require(staker_allowed_migrators[msg.sender][migrator_address] == false, "Address already exists");
require(valid_migrators[migrator_address], "Invalid migrator address");
staker_allowed_migrators[msg.sender][migrator_address] = true;
}
// Staker can disallow a previously-allowed migrator
function stakerDisallowMigrator(address migrator_address) public {
require(staker_allowed_migrators[msg.sender][migrator_address] == true, "Address doesn't exist already");
// Redundant
// require(valid_migrators[migrator_address], "Invalid migrator address");
// Delete from the mapping
delete staker_allowed_migrators[msg.sender][migrator_address];
}
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stake(uint256 amount) public {
_stake(msg.sender, msg.sender, amount);
}
// If this were not internal, and source_address had an infinite approve, this could be exploitable
// (pull funds from source_address and stake for an arbitrary staker_address)
function _stake(address staker_address, address source_address, uint256 amount) internal nonReentrant updateReward(staker_address) {
require((paused == false && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening");
require(amount > 0, "Cannot stake 0");
require(greylist[staker_address] == false, "address has been greylisted");
// Pull the tokens from the source_address
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.add(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.add(amount);
// Staking token balance and boosted balance
_unlocked_balances[staker_address] = _unlocked_balances[staker_address].add(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].add(amount);
emit Staked(staker_address, amount, source_address);
}
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stakeLocked(uint256 amount, uint256 secs) public {
_stakeLocked(msg.sender, msg.sender, amount, secs);
}
// If this were not internal, and source_address had an infinite approve, this could be exploitable
// (pull funds from source_address and stake for an arbitrary staker_address)
function _stakeLocked(address staker_address, address source_address, uint256 amount, uint256 secs) internal nonReentrant updateReward(staker_address) {
require((paused == false && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening");
require(amount > 0, "Cannot stake 0");
require(secs > 0, "Cannot wait for a negative number");
require(greylist[staker_address] == false, "address has been greylisted");
require(secs >= locked_stake_min_time, "Minimum stake time not met");
require(secs <= locked_stake_time_for_max_multiplier, "You are trying to stake for too long");
uint256 multiplier = stakingMultiplier(secs);
uint256 boostedAmount = amount.mul(multiplier).div(PRICE_PRECISION);
lockedStakes[staker_address].push(LockedStake(
keccak256(abi.encodePacked(staker_address, block.timestamp, amount)),
block.timestamp,
amount,
block.timestamp.add(secs),
multiplier
));
// Pull the tokens from the source_address
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.add(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.add(boostedAmount);
// Staking token balance and boosted balance
_locked_balances[staker_address] = _locked_balances[staker_address].add(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].add(boostedAmount);
emit StakeLocked(staker_address, amount, secs, source_address);
}
// Two different withdrawer functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdraw(uint256 amount) public {
_withdraw(msg.sender, msg.sender, amount);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked()
function _withdraw(address staker_address, address destination_address, uint256 amount) internal nonReentrant notWithdrawalsPaused updateReward(staker_address) {
require(amount > 0, "Cannot withdraw 0");
// Staking token balance and boosted balance
_unlocked_balances[staker_address] = _unlocked_balances[staker_address].sub(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].sub(amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.sub(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.sub(amount);
// Give the tokens to the destination_address
stakingToken.safeTransfer(destination_address, amount);
emit Withdrawn(staker_address, amount, destination_address);
}
// Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdrawLocked(bytes32 kek_id) public {
_withdrawLocked(msg.sender, msg.sender, kek_id);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked()
function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal nonReentrant notWithdrawalsPaused updateReward(staker_address) {
LockedStake memory thisStake;
thisStake.amount = 0;
uint theIndex;
for (uint i = 0; i < lockedStakes[staker_address].length; i++){
if (kek_id == lockedStakes[staker_address][i].kek_id){
thisStake = lockedStakes[staker_address][i];
theIndex = i;
break;
}
}
require(thisStake.kek_id == kek_id, "Stake not found");
require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!");
uint256 theAmount = thisStake.amount;
uint256 boostedAmount = theAmount.mul(thisStake.multiplier).div(PRICE_PRECISION);
if (theAmount > 0){
// Staking token balance and boosted balance
_locked_balances[staker_address] = _locked_balances[staker_address].sub(theAmount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].sub(boostedAmount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.sub(theAmount);
_staking_token_boosted_supply = _staking_token_boosted_supply.sub(boostedAmount);
// Remove the stake from the array
delete lockedStakes[staker_address][theIndex];
// Give the tokens to the destination_address
stakingToken.safeTransfer(destination_address, theAmount);
emit WithdrawnLocked(staker_address, theAmount, kek_id, destination_address);
}
}
// Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration)
function getReward() public {
_getReward(msg.sender, msg.sender);
}
// No withdrawer == msg.sender check needed since this is only internally callable
// This distinction is important for the migrator
function _getReward(address rewardee, address destination_address) internal nonReentrant notRewardsCollectionPaused updateReward(rewardee) {
uint256 reward0 = rewards0[rewardee];
uint256 reward1 = rewards1[rewardee];
if (reward0 > 0) {
rewards0[rewardee] = 0;
rewardsToken0.transfer(destination_address, reward0);
emit RewardPaid(rewardee, reward0, address(rewardsToken0), destination_address);
}
// if (token1_rewards_on){
if (reward1 > 0) {
rewards1[rewardee] = 0;
rewardsToken1.transfer(destination_address, reward1);
emit RewardPaid(rewardee, reward1, address(rewardsToken1), destination_address);
}
// }
}
function renewIfApplicable() external {
if (block.timestamp > periodFinish) {
retroCatchUp();
}
}
// If the period expired, renew it
function retroCatchUp() internal {
// Failsafe check
require(block.timestamp > periodFinish, "Period has not expired yet!");
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period
uint balance0 = rewardsToken0.balanceOf(address(this));
uint balance1 = rewardsToken1.balanceOf(address(this));
require(rewardRate0.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance0, "Not enough FXS available for rewards!");
if (token1_rewards_on){
require(rewardRate1.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance1, "Not enough token1 available for rewards!");
}
// uint256 old_lastUpdateTime = lastUpdateTime;
// uint256 new_lastUpdateTime = block.timestamp;
// lastUpdateTime = periodFinish;
periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration));
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
lastUpdateTime = lastTimeRewardApplicable();
emit RewardsPeriodRenewed(address(stakingToken));
}
function sync() public {
if (block.timestamp > periodFinish) {
retroCatchUp();
}
else {
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
lastUpdateTime = lastTimeRewardApplicable();
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can)
function migrator_stake_for(address staker_address, uint256 amount) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_stake(staker_address, msg.sender, amount);
}
// Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can).
function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_stakeLocked(staker_address, msg.sender, amount, secs);
}
// Used for migrations
function migrator_withdraw_unlocked(address staker_address) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_withdraw(staker_address, msg.sender, _unlocked_balances[staker_address]);
}
// Used for migrations
function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_withdrawLocked(staker_address, msg.sender, kek_id);
}
// Adds supported migrator address
function addMigrator(address migrator_address) public onlyByOwnerOrGovernance {
require(valid_migrators[migrator_address] == false, "address already exists");
valid_migrators[migrator_address] = true;
valid_migrators_array.push(migrator_address);
}
// Remove a migrator address
function removeMigrator(address migrator_address) public onlyByOwnerOrGovernance {
require(valid_migrators[migrator_address] == true, "address doesn't exist already");
// Delete from the mapping
delete valid_migrators[migrator_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < valid_migrators_array.length; i++){
if (valid_migrators_array[i] == migrator_address) {
valid_migrators_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
// Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders
function recoverBEP20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Admin cannot withdraw the staking token from the contract unless currently migrating
if(!migrationsOn){
require(tokenAddress != address(stakingToken), "Cannot withdraw staking tokens unless migration is on"); // Only Governance / Timelock can trigger a migration
}
// Only the owner address can ever receive the recovery withdrawal
BEP20(tokenAddress).transfer(owner_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance {
require(
periodFinish == 0 || block.timestamp > periodFinish,
"Previous rewards period must be complete before changing the duration for the new period"
);
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
function setMultipliers(uint256 _locked_stake_max_multiplier) external onlyByOwnerOrGovernance {
require(_locked_stake_max_multiplier >= 1, "Multiplier must be greater than or equal to 1");
locked_stake_max_multiplier = _locked_stake_max_multiplier;
emit LockedStakeMaxMultiplierUpdated(locked_stake_max_multiplier);
}
function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _locked_stake_time_for_max_multiplier, uint256 _locked_stake_min_time) external onlyByOwnerOrGovernance {
require(_locked_stake_time_for_max_multiplier >= 1, "Multiplier Max Time must be greater than or equal to 1");
require(_locked_stake_min_time >= 1, "Multiplier Min Time must be greater than or equal to 1");
locked_stake_time_for_max_multiplier = _locked_stake_time_for_max_multiplier;
locked_stake_min_time = _locked_stake_min_time;
emit LockedStakeTimeForMaxMultiplier(locked_stake_time_for_max_multiplier);
emit LockedStakeMinTime(_locked_stake_min_time);
}
function initializeDefault() external onlyByOwnerOrGovernance {
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit DefaultInitialization();
}
function greylistAddress(address _address) external onlyByOwnerOrGovernance {
greylist[_address] = !(greylist[_address]);
}
function unlockStakes() external onlyByOwnerOrGovernance {
stakesUnlocked = !stakesUnlocked;
}
function toggleMigrations() external onlyByOwnerOrGovernance {
migrationsOn = !migrationsOn;
}
function toggleWithdrawals() external onlyByOwnerOrGovernance {
withdrawalsPaused = !withdrawalsPaused;
}
function toggleRewardsCollection() external onlyByOwnerOrGovernance {
rewardsCollectionPaused = !rewardsCollectionPaused;
}
function setRewardRates(uint256 _new_rate0, uint256 _new_rate1, bool sync_too) external onlyByOwnerOrGovernance {
rewardRate0 = _new_rate0;
rewardRate1 = _new_rate1;
if (sync_too){
sync();
}
}
function toggleToken1Rewards() external onlyByOwnerOrGovernance {
if (token1_rewards_on) {
rewardRate1 = 0;
}
token1_rewards_on = !token1_rewards_on;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setTimelock(address _new_timelock) external onlyByOwnerOrGovernance {
timelock_address = _new_timelock;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount, address source_address );
event StakeLocked(address indexed user, uint256 amount, uint256 secs, address source_address);
event Withdrawn(address indexed user, uint256 amount, address destination_address);
event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address);
event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event RewardsPeriodRenewed(address token);
event DefaultInitialization();
event LockedStakeMaxMultiplierUpdated(uint256 multiplier);
event LockedStakeTimeForMaxMultiplier(uint256 secs);
event LockedStakeMinTime(uint256 secs);
}
| Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders Admin cannot withdraw the staking token from the contract unless currently migrating | function recoverBEP20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
if(!migrationsOn){
}
emit Recovered(tokenAddress, tokenAmount);
}
| 7,271,229 | [
1,
8602,
358,
2865,
5910,
310,
511,
52,
534,
359,
14727,
471,
1308,
27228,
7940,
2430,
628,
1308,
14908,
358,
506,
16859,
358,
366,
4665,
7807,
2780,
598,
9446,
326,
384,
6159,
1147,
628,
326,
6835,
3308,
4551,
4196,
1776,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
5910,
5948,
52,
3462,
12,
2867,
1147,
1887,
16,
2254,
5034,
1147,
6275,
13,
3903,
1338,
858,
5541,
1162,
43,
1643,
82,
1359,
288,
203,
3639,
309,
12,
5,
15642,
1398,
15329,
203,
3639,
289,
203,
3639,
3626,
868,
16810,
12,
2316,
1887,
16,
1147,
6275,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-18
*/
/**
// Baby EPRO ($BEPRO) ;
// Web: https://babyepro.co ;
// Telegram: https://t.me/BabyEPROToken ;
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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;
}
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;
}
// Contract implementation
contract BEPRO is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Baby EPRO';
string private _symbol = 'BEPRO';
uint8 private _decimals = 9;
// Tax and team fees will start at 0 so we don't have a big impact when deploying to Uniswap
// Team wallet address is null but the method to set the address is exposed
uint256 private _taxFee = 2;
uint256 private _teamFee = 0;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousTeamFee = _teamFee;
address payable public _teamWalletAddress;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
bool public _MaxBuyEnabled = false;
uint256 private _maxTxAmount = 10000000000000 * 10**9;
uint256 private _maxBuy = 10000000000 * 10**9;
// We will set a minimum amount of tokens to be swaped => 5M
uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable teamWalletAddress, address payable marketingWalletAddress) public {
_teamWalletAddress = teamWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_teamWalletAddress] = true;
_isExcludedFromFee[_marketingWalletAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_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 isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousTeamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousTeamFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_MaxBuyEnabled){
if(sender == uniswapV2Pair && recipient != owner() && sender != owner()){
require (amount <= _maxBuy);
}
}
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular team event.
// also, don't swap if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair && sender != address(uniswapV2Router)
) {
// We need to swap the current tokens to ETH and send to the team wallet
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
//transfer amount, it will take tax and team fee
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
// 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 sendETHToTeam(uint256 amount) private {
_teamWalletAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToTeam(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function setMaxBuyEnabled(bool MaxBuyEnabled) external onlyOwner(){
_MaxBuyEnabled = MaxBuyEnabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(teamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25');
_taxFee = taxFee;
}
function _setTeamFee(uint256 teamFee) external onlyOwner() {
require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25');
_teamFee = teamFee;
}
function _setTeamWallet(address payable teamWalletAddress) external onlyOwner() {
_teamWalletAddress = teamWalletAddress;
}
function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() {
_marketingWalletAddress = marketingWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9');
_maxTxAmount = maxTxAmount;
}
function recoverTokens(uint256 tokenAmount) public virtual onlyOwner() {
_approve(address(this), owner(), tokenAmount);
_transfer(address(this), owner(), tokenAmount);
}
} | Contract implementation Tax and team fees will start at 0 so we don't have a big impact when deploying to Uniswap Team wallet address is null but the method to set the address is exposed We will set a minimum amount of tokens to be swaped => 5M | contract BEPRO is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Baby EPRO';
string private _symbol = 'BEPRO';
uint8 private _decimals = 9;
uint256 private _taxFee = 2;
uint256 private _teamFee = 0;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousTeamFee = _teamFee;
address payable public _teamWalletAddress;
address payable public _marketingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
bool public _MaxBuyEnabled = false;
uint256 private _maxTxAmount = 10000000000000 * 10**9;
uint256 private _maxBuy = 10000000000 * 10**9;
uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable teamWalletAddress, address payable marketingWalletAddress) public {
_teamWalletAddress = teamWalletAddress;
_marketingWalletAddress = marketingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_teamWalletAddress] = true;
_isExcludedFromFee[_marketingWalletAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_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 isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousTeamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousTeamFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_MaxBuyEnabled){
if(sender == uniswapV2Pair && recipient != owner() && sender != owner()){
require (amount <= _maxBuy);
}
}
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair && sender != address(uniswapV2Router)
) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_MaxBuyEnabled){
if(sender == uniswapV2Pair && recipient != owner() && sender != owner()){
require (amount <= _maxBuy);
}
}
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair && sender != address(uniswapV2Router)
) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_MaxBuyEnabled){
if(sender == uniswapV2Pair && recipient != owner() && sender != owner()){
require (amount <= _maxBuy);
}
}
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair && sender != address(uniswapV2Router)
) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_MaxBuyEnabled){
if(sender == uniswapV2Pair && recipient != owner() && sender != owner()){
require (amount <= _maxBuy);
}
}
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair && sender != address(uniswapV2Router)
) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_MaxBuyEnabled){
if(sender == uniswapV2Pair && recipient != owner() && sender != owner()){
require (amount <= _maxBuy);
}
}
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair && sender != address(uniswapV2Router)
) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_MaxBuyEnabled){
if(sender == uniswapV2Pair && recipient != owner() && sender != owner()){
require (amount <= _maxBuy);
}
}
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair && sender != address(uniswapV2Router)
) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
bool takeFee = true;
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(_MaxBuyEnabled){
if(sender == uniswapV2Pair && recipient != owner() && sender != owner()){
require (amount <= _maxBuy);
}
}
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair && sender != address(uniswapV2Router)
) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
_tokenTransfer(sender,recipient,amount,takeFee);
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function sendETHToTeam(uint256 amount) private {
_teamWalletAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToTeam(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function setMaxBuyEnabled(bool MaxBuyEnabled) external onlyOwner(){
_MaxBuyEnabled = MaxBuyEnabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(teamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25');
_taxFee = taxFee;
}
function _setTeamFee(uint256 teamFee) external onlyOwner() {
require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25');
_teamFee = teamFee;
}
function _setTeamWallet(address payable teamWalletAddress) external onlyOwner() {
_teamWalletAddress = teamWalletAddress;
}
function _setMarketingWallet(address payable marketingWalletAddress) external onlyOwner() {
_marketingWalletAddress = marketingWalletAddress;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9');
_maxTxAmount = maxTxAmount;
}
function recoverTokens(uint256 tokenAmount) public virtual onlyOwner() {
_approve(address(this), owner(), tokenAmount);
_transfer(address(this), owner(), tokenAmount);
}
} | 15,137,983 | [
1,
8924,
4471,
18240,
471,
5927,
1656,
281,
903,
787,
622,
374,
1427,
732,
2727,
1404,
1240,
279,
5446,
15800,
1347,
7286,
310,
358,
1351,
291,
91,
438,
10434,
9230,
1758,
353,
446,
1496,
326,
707,
358,
444,
326,
1758,
353,
16265,
1660,
903,
444,
279,
5224,
3844,
434,
2430,
358,
506,
1352,
5994,
516,
1381,
49,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
6835,
9722,
3373,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
3639,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
3639,
1450,
5267,
364,
1758,
31,
203,
203,
3639,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
3639,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
3639,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
203,
3639,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
3639,
1758,
8526,
3238,
389,
24602,
31,
203,
377,
203,
3639,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
3639,
2254,
5034,
3238,
389,
88,
5269,
273,
15088,
9449,
380,
1728,
636,
29,
31,
203,
3639,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
3639,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
3639,
533,
3238,
389,
529,
273,
296,
38,
24383,
512,
3373,
13506,
203,
3639,
533,
3238,
389,
7175,
273,
296,
5948,
3373,
13506,
203,
3639,
2254,
28,
3238,
389,
31734,
273,
2468,
31,
203,
540,
203,
3639,
2254,
5034,
3238,
389,
8066,
14667,
273,
576,
31,
7010,
3639,
2254,
5034,
3238,
389,
10035,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
3238,
389,
11515,
7731,
14667,
273,
389,
8066,
14667,
31,
203,
3639,
2
] |
pragma solidity 0.5.17;
import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import {TBTCDepositToken} from "./TBTCDepositToken.sol";
import {FeeRebateToken} from "./FeeRebateToken.sol";
import {TBTCToken} from "./TBTCToken.sol";
import {TBTCConstants} from "./TBTCConstants.sol";
import "../deposit/Deposit.sol";
import "./TBTCSystemAuthority.sol";
/// @title Vending Machine
/// @notice The Vending Machine swaps TDTs (`TBTCDepositToken`)
/// to TBTC (`TBTCToken`) and vice versa.
/// @dev The Vending Machine should have exclusive TBTC and FRT (`FeeRebateToken`) minting
/// privileges.
contract VendingMachine is TBTCSystemAuthority{
using SafeMath for uint256;
TBTCToken tbtcToken;
TBTCDepositToken tbtcDepositToken;
FeeRebateToken feeRebateToken;
uint256 createdAt;
constructor(address _systemAddress)
TBTCSystemAuthority(_systemAddress)
public {
createdAt = block.timestamp;
}
/// @notice Set external contracts needed by the Vending Machine.
/// @dev Addresses are used to update the local contract instance.
/// @param _tbtcToken TBTCToken contract. More info in `TBTCToken`.
/// @param _tbtcDepositToken TBTCDepositToken (TDT) contract. More info in `TBTCDepositToken`.
/// @param _feeRebateToken FeeRebateToken (FRT) contract. More info in `FeeRebateToken`.
function setExternalAddresses(
TBTCToken _tbtcToken,
TBTCDepositToken _tbtcDepositToken,
FeeRebateToken _feeRebateToken
) external onlyTbtcSystem {
tbtcToken = _tbtcToken;
tbtcDepositToken = _tbtcDepositToken;
feeRebateToken = _feeRebateToken;
}
/// @notice Burns TBTC and transfers the tBTC Deposit Token to the caller
/// as long as it is qualified.
/// @dev We burn the lotSize of the Deposit in order to maintain
/// the TBTC supply peg in the Vending Machine. VendingMachine must be approved
/// by the caller to burn the required amount.
/// @param _tdtId ID of tBTC Deposit Token to buy.
function tbtcToTdt(uint256 _tdtId) external {
require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist");
require(isQualified(address(_tdtId)), "Deposit must be qualified");
uint256 depositValue = Deposit(address(uint160(_tdtId))).lotSizeTbtc();
require(tbtcToken.balanceOf(msg.sender) >= depositValue, "Not enough TBTC for TDT exchange");
tbtcToken.burnFrom(msg.sender, depositValue);
// TODO do we need the owner check below? transferFrom can be approved for a user, which might be an interesting use case.
require(tbtcDepositToken.ownerOf(_tdtId) == address(this), "Deposit is locked");
tbtcDepositToken.transferFrom(address(this), msg.sender, _tdtId);
}
/// @notice Transfer the tBTC Deposit Token and mint TBTC.
/// @dev Transfers TDT from caller to vending machine, and mints TBTC to caller.
/// Vending Machine must be approved to transfer TDT by the caller.
/// @param _tdtId ID of tBTC Deposit Token to sell.
function tdtToTbtc(uint256 _tdtId) public {
require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist");
require(isQualified(address(_tdtId)), "Deposit must be qualified");
tbtcDepositToken.transferFrom(msg.sender, address(this), _tdtId);
Deposit deposit = Deposit(address(uint160(_tdtId)));
uint256 signerFee = deposit.signerFeeTbtc();
uint256 depositValue = deposit.lotSizeTbtc();
require(canMint(depositValue), "Can't mint more than the max supply cap");
// If the backing Deposit does not have a signer fee in escrow, mint it.
if(tbtcToken.balanceOf(address(_tdtId)) < signerFee) {
tbtcToken.mint(msg.sender, depositValue.sub(signerFee));
tbtcToken.mint(address(_tdtId), signerFee);
}
else{
tbtcToken.mint(msg.sender, depositValue);
}
// owner of the TDT during first TBTC mint receives the FRT
if(!feeRebateToken.exists(_tdtId)){
feeRebateToken.mint(msg.sender, _tdtId);
}
}
/// @notice Return whether an amount of TBTC can be minted according to the supply cap
/// schedule
/// @dev This function is also used by TBTCSystem to decide whether to allow a new deposit.
/// @return True if the amount can be minted without hitting the max supply, false otherwise.
function canMint(uint256 amount) public view returns (bool) {
return getMintedSupply().add(amount) < getMaxSupply();
}
/// @notice Determines whether a deposit is qualified for minting TBTC.
/// @param _depositAddress The address of the deposit
function isQualified(address payable _depositAddress) public view returns (bool) {
return Deposit(_depositAddress).inActive();
}
/// @notice Return the minted TBTC supply in weitoshis (BTC * 10 ** 18).
function getMintedSupply() public view returns (uint256) {
return tbtcToken.totalSupply();
}
/// @notice Get the maximum TBTC token supply based on the age of the
/// contract deployment. The supply cap starts at 2 BTC for the two
/// days, 100 for the first week, 250 for the next, then 500, 750,
/// 1000, 1500, 2000, 2500, and 3000... finally removing the minting
/// restriction after 9 weeks and returning 21M BTC as a sanity
/// check.
/// @return The max supply in weitoshis (BTC * 10 ** 18).
function getMaxSupply() public view returns (uint256) {
uint256 age = block.timestamp - createdAt;
if(age < 2 days) {
return 2 * 10 ** 18;
}
if (age < 7 days) {
return 100 * 10 ** 18;
}
if (age < 14 days) {
return 250 * 10 ** 18;
}
if (age < 21 days) {
return 500 * 10 ** 18;
}
if (age < 28 days) {
return 750 * 10 ** 18;
}
if (age < 35 days) {
return 1000 * 10 ** 18;
}
if (age < 42 days) {
return 1500 * 10 ** 18;
}
if (age < 49 days) {
return 2000 * 10 ** 18;
}
if (age < 56 days) {
return 2500 * 10 ** 18;
}
if (age < 63 days) {
return 3000 * 10 ** 18;
}
return 21e6 * 10 ** 18;
}
// WRAPPERS
/// @notice Qualifies a deposit and mints TBTC.
/// @dev User must allow VendingManchine to transfer TDT.
function unqualifiedDepositToTbtc(
address payable _depositAddress,
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public { // not external to allow bytes memory parameters
Deposit _d = Deposit(_depositAddress);
_d.provideBTCFundingProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_fundingOutputIndex,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
tdtToTbtc(uint256(_depositAddress));
}
/// @notice Redeems a Deposit by purchasing a TDT with TBTC for _finalRecipient,
/// and using the TDT to redeem corresponding Deposit as _finalRecipient.
/// This function will revert if the Deposit is not in ACTIVE state.
/// @dev Vending Machine transfers TBTC allowance to Deposit.
/// @param _depositAddress The address of the Deposit to redeem.
/// @param _outputValueBytes The 8-byte Bitcoin transaction output size in Little Endian.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
function tbtcToBtc(
address payable _depositAddress,
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript
) public { // not external to allow bytes memory parameters
require(tbtcDepositToken.exists(uint256(_depositAddress)), "tBTC Deposit Token does not exist");
Deposit _d = Deposit(_depositAddress);
tbtcToken.burnFrom(msg.sender, _d.lotSizeTbtc());
tbtcDepositToken.approve(_depositAddress, uint256(_depositAddress));
uint256 tbtcOwed = _d.getOwnerRedemptionTbtcRequirement(msg.sender);
if(tbtcOwed != 0){
tbtcToken.transferFrom(msg.sender, address(this), tbtcOwed);
tbtcToken.approve(_depositAddress, tbtcOwed);
}
_d.transferAndRequestRedemption(_outputValueBytes, _redeemerOutputScript, msg.sender);
}
}
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;
}
}
pragma solidity 0.5.17;
/**
* @title Keep interface
*/
interface ITBTCSystem {
// expected behavior:
// return the price of 1 sat in wei
// these are the native units of the deposit contract
function fetchBitcoinPrice() external view returns (uint256);
// passthrough requests for the oracle
function fetchRelayCurrentDifficulty() external view returns (uint256);
function fetchRelayPreviousDifficulty() external view returns (uint256);
function getNewDepositFeeEstimate() external view returns (uint256);
function getAllowNewDeposits() external view returns (bool);
function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) external view returns (bool);
function requestNewKeep(uint64 _requestedLotSizeSatoshis, uint256 _maxSecuredLifetime) external payable returns (address);
function getSignerFeeDivisor() external view returns (uint16);
function getInitialCollateralizedPercent() external view returns (uint16);
function getUndercollateralizedThresholdPercent() external view returns (uint16);
function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16);
}
pragma solidity 0.5.17;
import {DepositLiquidation} from "./DepositLiquidation.sol";
import {DepositUtils} from "./DepositUtils.sol";
import {DepositFunding} from "./DepositFunding.sol";
import {DepositRedemption} from "./DepositRedemption.sol";
import {DepositStates} from "./DepositStates.sol";
import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol";
import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {FeeRebateToken} from "../system/FeeRebateToken.sol";
import "../system/DepositFactoryAuthority.sol";
// solium-disable function-order
// Below, a few functions must be public to allow bytes memory parameters, but
// their being so triggers errors because public functions should be grouped
// below external functions. Since these would be external if it were possible,
// we ignore the issue.
/// @title tBTC Deposit
/// @notice This is the main contract for tBTC. It is the state machine that
/// (through various libraries) handles bitcoin funding, bitcoin-spv
/// proofs, redemption, liquidation, and fraud logic.
/// @dev This contract presents a public API that exposes the following
/// libraries:
///
/// - `DepositFunding`
/// - `DepositLiquidaton`
/// - `DepositRedemption`,
/// - `DepositStates`
/// - `DepositUtils`
/// - `OutsourceDepositLogging`
/// - `TBTCConstants`
///
/// Where these libraries require deposit state, this contract's state
/// variable `self` is used. `self` is a struct of type
/// `DepositUtils.Deposit` that contains all aspects of the deposit state
/// itself.
contract Deposit is DepositFactoryAuthority {
using DepositRedemption for DepositUtils.Deposit;
using DepositFunding for DepositUtils.Deposit;
using DepositLiquidation for DepositUtils.Deposit;
using DepositUtils for DepositUtils.Deposit;
using DepositStates for DepositUtils.Deposit;
DepositUtils.Deposit self;
/// @dev Deposit should only be _constructed_ once. New deposits are created
/// using the `DepositFactory.createDeposit` method, and are clones of
/// the constructed deposit. The factory will set the initial values
/// for a new clone using `initializeDeposit`.
constructor () public {
// The constructed Deposit will never be used, so the deposit factory
// address can be anything. Clones are updated as per above.
initialize(address(0xdeadbeef));
}
/// @notice Deposits do not accept arbitrary ETH.
function () external payable {
require(msg.data.length == 0, "Deposit contract was called with unknown function selector.");
}
//----------------------------- METADATA LOOKUP ------------------------------//
/// @notice Get this deposit's BTC lot size in satoshis.
/// @return uint64 lot size in satoshis.
function lotSizeSatoshis() external view returns (uint64){
return self.lotSizeSatoshis;
}
/// @notice Get this deposit's lot size in TBTC.
/// @dev This is the same as lotSizeSatoshis(), but is multiplied to scale
/// to 18 decimal places.
/// @return uint256 lot size in TBTC precision (max 18 decimal places).
function lotSizeTbtc() external view returns (uint256){
return self.lotSizeTbtc();
}
/// @notice Get the signer fee for this deposit, in TBTC.
/// @dev This is the one-time fee required by the signers to perform the
/// tasks needed to maintain a decentralized and trustless model for
/// tBTC. It is a percentage of the deposit's lot size.
/// @return Fee amount in TBTC.
function signerFeeTbtc() external view returns (uint256) {
return self.signerFeeTbtc();
}
/// @notice Get the integer representing the current state.
/// @dev We implement this because contracts don't handle foreign enums
/// well. See `DepositStates` for more info on states.
/// @return The 0-indexed state from the DepositStates enum.
function currentState() external view returns (uint256) {
return uint256(self.currentState);
}
/// @notice Check if the Deposit is in ACTIVE state.
/// @return True if state is ACTIVE, false otherwise.
function inActive() external view returns (bool) {
return self.inActive();
}
/// @notice Get the contract address of the BondedECDSAKeep associated with
/// this Deposit.
/// @dev The keep contract address is saved on Deposit initialization.
/// @return Address of the Keep contract.
function keepAddress() external view returns (address) {
return self.keepAddress;
}
/// @notice Retrieve the remaining term of the deposit in seconds.
/// @dev The value accuracy is not guaranteed since block.timestmap can be
/// lightly manipulated by miners.
/// @return The remaining term of the deposit in seconds. 0 if already at
/// term.
function remainingTerm() external view returns(uint256){
return self.remainingTerm();
}
/// @notice Get the current collateralization level for this Deposit.
/// @dev This value represents the percentage of the backing BTC value the
/// signers currently must hold as bond.
/// @return The current collateralization level for this deposit.
function collateralizationPercentage() external view returns (uint256) {
return self.collateralizationPercentage();
}
/// @notice Get the initial collateralization level for this Deposit.
/// @dev This value represents the percentage of the backing BTC value
/// the signers hold initially. It is set at creation time.
/// @return The initial collateralization level for this deposit.
function initialCollateralizedPercent() external view returns (uint16) {
return self.initialCollateralizedPercent;
}
/// @notice Get the undercollateralization level for this Deposit.
/// @dev This collateralization level is semi-critical. If the
/// collateralization level falls below this percentage the Deposit can
/// be courtesy-called by calling `notifyCourtesyCall`. This value
/// represents the percentage of the backing BTC value the signers must
/// hold as bond in order to not be undercollateralized. It is set at
/// creation time. Note that the value for new deposits in TBTCSystem
/// can be changed by governance, but the value for a particular
/// deposit is static once the deposit is created.
/// @return The undercollateralized level for this deposit.
function undercollateralizedThresholdPercent() external view returns (uint16) {
return self.undercollateralizedThresholdPercent;
}
/// @notice Get the severe undercollateralization level for this Deposit.
/// @dev This collateralization level is critical. If the collateralization
/// level falls below this percentage the Deposit can get liquidated.
/// This value represents the percentage of the backing BTC value the
/// signers must hold as bond in order to not be severely
/// undercollateralized. It is set at creation time. Note that the
/// value for new deposits in TBTCSystem can be changed by governance,
/// but the value for a particular deposit is static once the deposit
/// is created.
/// @return The severely undercollateralized level for this deposit.
function severelyUndercollateralizedThresholdPercent() external view returns (uint16) {
return self.severelyUndercollateralizedThresholdPercent;
}
/// @notice Get the value of the funding UTXO.
/// @dev This call will revert if the deposit is not in a state where the
/// UTXO info should be valid. In particular, before funding proof is
/// successfully submitted (i.e. in states START,
/// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), this value
/// would not be valid.
/// @return The value of the funding UTXO in satoshis.
function utxoValue() external view returns (uint256){
require(
! self.inFunding(),
"Deposit has not yet been funded and has no available funding info"
);
return self.utxoValue();
}
/// @notice Returns information associated with the funding UXTO.
/// @dev This call will revert if the deposit is not in a state where the
/// funding info should be valid. In particular, before funding proof
/// is successfully submitted (i.e. in states START,
/// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of
/// these values are set or valid.
/// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint).
function fundingInfo() external view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) {
require(
! self.inFunding(),
"Deposit has not yet been funded and has no available funding info"
);
return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint);
}
/// @notice Calculates the amount of value at auction right now.
/// @dev This call will revert if the deposit is not in a state where an
/// auction is currently in progress.
/// @return The value in wei that would be received in exchange for the
/// deposit's lot size in TBTC if `purchaseSignerBondsAtAuction`
/// were called at the time this function is called.
function auctionValue() external view returns (uint256) {
require(
self.inSignerLiquidation(),
"Deposit has no funds currently at auction"
);
return self.auctionValue();
}
/// @notice Get caller's ETH withdraw allowance.
/// @dev Generally ETH is only available to withdraw after the deposit
/// reaches a closed state. The amount reported is for the sender, and
/// can be withdrawn using `withdrawFunds` if the deposit is in an end
/// state.
/// @return The withdraw allowance in wei.
function withdrawableAmount() external view returns (uint256) {
return self.getWithdrawableAmount();
}
//------------------------------ FUNDING FLOW --------------------------------//
/// @notice Notify the contract that signing group setup has timed out if
/// retrieveSignerPubkey is not successfully called within the
/// allotted time.
/// @dev This is considered a signer fault, and the signers' bonds are used
/// to make the deposit setup fee available for withdrawal by the TDT
/// holder as a refund. The remainder of the signers' bonds are
/// returned to the bonding pool and the signers are released from any
/// further responsibilities. Reverts if the deposit is not awaiting
/// signer setup or if the signing group formation timeout has not
/// elapsed.
function notifySignerSetupFailed() external {
self.notifySignerSetupFailed();
}
/// @notice Notify the contract that the ECDSA keep has generated a public
/// key so the deposit contract can pull it in.
/// @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a
/// RegisteredPubkey event with the two components. Reverts if the
/// deposit is not awaiting signer setup, if the generated public key
/// is unset or has incorrect length, or if the public key has a 0
/// X or Y value.
function retrieveSignerPubkey() external {
self.retrieveSignerPubkey();
}
/// @notice Notify the contract that the funding phase of the deposit has
/// timed out if `provideBTCFundingProof` is not successfully called
/// within the allotted time. Any sent BTC is left under control of
/// the signer group, and the funder can use `requestFunderAbort` to
/// request an at-signer-discretion return of any BTC sent to a
/// deposit that has been notified of a funding timeout.
/// @dev This is considered a funder fault, and the funder's payment for
/// opening the deposit is not refunded. Emits a SetupFailed event.
/// Reverts if the funding timeout has not yet elapsed, or if the
/// deposit is not currently awaiting funding proof.
function notifyFundingTimedOut() external {
self.notifyFundingTimedOut();
}
/// @notice Requests a funder abort for a failed-funding deposit; that is,
/// requests the return of a sent UTXO to _abortOutputScript. It
/// imposes no requirements on the signing group. Signers should
/// send their UTXO to the requested output script, but do so at
/// their discretion and with no penalty for failing to do so. This
/// can be used for example when a UTXO is sent that is the wrong
/// size for the lot.
/// @dev This is a self-admitted funder fault, and is only be callable by
/// the TDT holder. This function emits the FunderAbortRequested event,
/// but stores no additional state.
/// @param _abortOutputScript The output script the funder wishes to request
/// a return of their UTXO to.
function requestFunderAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters
require(
self.depositOwner() == msg.sender,
"Only TDT holder can request funder abort"
);
self.requestFunderAbort(_abortOutputScript);
}
/// @notice Anyone can provide a signature corresponding to the signers'
/// public key to prove fraud during funding. Note that during
/// funding no signature has been requested from the signers, so
/// any signature is effectively fraud.
/// @dev Calls out to the keep to verify if there was fraud.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature (v,r,s) tuple.
/// @param _preimage The sha256 preimage of the digest.
function provideFundingECDSAFraudProof(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public { // not external to allow bytes memory parameters
self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage);
}
/// @notice Anyone may submit a funding proof to the deposit showing that
/// a transaction was submitted and sufficiently confirmed on the
/// Bitcoin chain transferring the deposit lot size's amount of BTC
/// to the signer-controlled private key corresopnding to this
/// deposit. This will move the deposit into an active state.
/// @dev Takes a pre-parsed transaction and calculates values needed to
/// verify funding.
/// @param _txVersion Transaction version number (4-byte little-endian).
/// @param _txInputVector All transaction inputs prepended by the number of
/// inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number
/// of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _fundingOutputIndex Index of funding output in _txOutputVector
/// (0-indexed).
/// @param _merkleProof The merkle proof of transaction inclusion in a
/// block.
/// @param _txIndexInBlock Transaction index in the block (0-indexed).
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers,
/// lowest height first.
function provideBTCFundingProof(
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public { // not external to allow bytes memory parameters
self.provideBTCFundingProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_fundingOutputIndex,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
}
//---------------------------- LIQUIDATION FLOW ------------------------------//
/// @notice Notify the contract that the signers are undercollateralized.
/// @dev This call will revert if the signers are not in fact
/// undercollateralized according to the price feed. After
/// TBTCConstants.COURTESY_CALL_DURATION, courtesy call times out and
/// regular abort liquidation occurs; see
/// `notifyCourtesyTimedOut`.
function notifyCourtesyCall() external {
self.notifyCourtesyCall();
}
/// @notice Notify the contract that the signers' bond value has recovered
/// enough to be considered sufficiently collateralized.
/// @dev This call will revert if collateral is still below the
/// undercollateralized threshold according to the price feed.
function exitCourtesyCall() external {
self.exitCourtesyCall();
}
/// @notice Notify the contract that the courtesy period has expired and the
/// deposit should move into liquidation.
/// @dev This call will revert if the courtesy call period has not in fact
/// expired or is not in the courtesy call state. Courtesy call
/// expiration is treated as an abort, and is handled by seizing signer
/// bonds and putting them up for auction for the lot size amount in
/// TBTC (see `purchaseSignerBondsAtAuction`). Emits a
/// LiquidationStarted event. The caller is captured as the liquidation
/// initiator, and is eligible for 50% of any bond left after the
/// auction is completed.
function notifyCourtesyCallExpired() external {
self.notifyCourtesyCallExpired();
}
/// @notice Notify the contract that the signers are undercollateralized.
/// @dev Calls out to the system for oracle info.
/// @dev This call will revert if the signers are not in fact severely
/// undercollateralized according to the price feed. Severe
/// undercollateralization is treated as an abort, and is handled by
/// seizing signer bonds and putting them up for auction in exchange
/// for the lot size amount in TBTC (see
/// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event.
/// The caller is captured as the liquidation initiator, and is
/// eligible for 50% of any bond left after the auction is completed.
function notifyUndercollateralizedLiquidation() external {
self.notifyUndercollateralizedLiquidation();
}
/// @notice Anyone can provide a signature corresponding to the signers'
/// public key that was not requested to prove fraud. A redemption
/// request and a redemption fee increase are the only ways to
/// request a signature from the signers.
/// @dev This call will revert if the underlying keep cannot verify that
/// there was fraud. Fraud is handled by seizing signer bonds and
/// putting them up for auction in exchange for the lot size amount in
/// TBTC (see `purchaseSignerBondsAtAuction`). Emits a
/// LiquidationStarted event. The caller is captured as the liquidation
/// initiator, and is eligible for any bond left after the auction is
/// completed.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature (v,r,s) tuple.
/// @param _preimage The sha256 preimage of the digest.
function provideECDSAFraudProof(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public { // not external to allow bytes memory parameters
self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage);
}
/// @notice Notify the contract that the signers have failed to produce a
/// signature for a redemption request in the allotted time.
/// @dev This is considered an abort, and is punished by seizing signer
/// bonds and putting them up for auction. Emits a LiquidationStarted
/// event and a Liquidated event and sends the full signer bond to the
/// redeemer. Reverts if the deposit is not currently awaiting a
/// signature or if the allotted time has not yet elapsed. The caller
/// is captured as the liquidation initiator, and is eligible for 50%
/// of any bond left after the auction is completed.
function notifyRedemptionSignatureTimedOut() external {
self.notifyRedemptionSignatureTimedOut();
}
/// @notice Notify the contract that the deposit has failed to receive a
/// redemption proof in the allotted time.
/// @dev This call will revert if the deposit is not currently awaiting a
/// signature or if the allotted time has not yet elapsed. This is
/// considered an abort, and is punished by seizing signer bonds and
/// putting them up for auction for the lot size amount in TBTC (see
/// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event.
/// The caller is captured as the liquidation initiator, and
/// is eligible for 50% of any bond left after the auction is
/// completed.
function notifyRedemptionProofTimedOut() external {
self.notifyRedemptionProofTimedOut();
}
/// @notice Closes an auction and purchases the signer bonds by transferring
/// the lot size in TBTC to the redeemer, if there is one, or to the
/// TDT holder if not. Any bond amount that is not currently up for
/// auction is either made available for the liquidation initiator
/// to withdraw (for fraud) or split 50-50 between the initiator and
/// the signers (for abort or collateralization issues).
/// @dev The amount of ETH given for the transferred TBTC can be read using
/// the `auctionValue` function; note, however, that the function's
/// value is only static during the specific block it is queried, as it
/// varies by block timestamp.
function purchaseSignerBondsAtAuction() external {
self.purchaseSignerBondsAtAuction();
}
//---------------------------- REDEMPTION FLOW -------------------------------//
/// @notice Get TBTC amount required for redemption by a specified
/// _redeemer.
/// @dev This call will revert if redemption is not possible by _redeemer.
/// @param _redeemer The deposit redeemer whose TBTC requirement is being
/// requested.
/// @return The amount in TBTC needed by the `_redeemer` to redeem the
/// deposit.
function getRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){
(uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, false);
return tbtcPayment;
}
/// @notice Get TBTC amount required for redemption assuming _redeemer
/// is this deposit's owner (TDT holder).
/// @param _redeemer The assumed owner of the deposit's TDT .
/// @return The amount in TBTC needed to redeem the deposit.
function getOwnerRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){
(uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, true);
return tbtcPayment;
}
/// @notice Requests redemption of this deposit, meaning the transmission,
/// by the signers, of the deposit's UTXO to the specified Bitocin
/// output script. Requires approving the deposit to spend the
/// amount of TBTC needed to redeem.
/// @dev The amount of TBTC needed to redeem can be looked up using the
/// `getRedemptionTbtcRequirement` or `getOwnerRedemptionTbtcRequirement`
/// functions.
/// @param _outputValueBytes The 8-byte little-endian output size. The
/// difference between this value and the lot size of the deposit
/// will be paid as a fee to the Bitcoin miners when the signed
/// transaction is broadcast.
/// @param _redeemerOutputScript The redeemer's length-prefixed output
/// script.
function requestRedemption(
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript
) public { // not external to allow bytes memory parameters
self.requestRedemption(_outputValueBytes, _redeemerOutputScript);
}
/// @notice Anyone may provide a withdrawal signature if it was requested.
/// @dev The signers will be penalized if this function is not called
/// correctly within `TBTCConstants.REDEMPTION_SIGNATURE_TIMEOUT`
/// seconds of a redemption request or fee increase being received.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value. Should be in the low half of secp256k1
/// curve's order.
function provideRedemptionSignature(
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
self.provideRedemptionSignature(_v, _r, _s);
}
/// @notice Anyone may request a signature for a transaction with an
/// increased Bitcoin transaction fee.
/// @dev This call will revert if the fee is already at its maximum, or if
/// the new requested fee is not a multiple of the initial requested
/// fee. Transaction fees can only be bumped by the amount of the
/// initial requested fee. Calling this sends the deposit back to
/// the `AWAITING_WITHDRAWAL_SIGNATURE` state and requires the signers
/// to `provideRedemptionSignature` for the new output value in a
/// timely fashion.
/// @param _previousOutputValueBytes The previous output's value.
/// @param _newOutputValueBytes The new output's value.
function increaseRedemptionFee(
bytes8 _previousOutputValueBytes,
bytes8 _newOutputValueBytes
) external {
self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes);
}
/// @notice Anyone may submit a redemption proof to the deposit showing that
/// a transaction was submitted and sufficiently confirmed on the
/// Bitcoin chain transferring the deposit lot size's amount of BTC
/// from the signer-controlled private key corresponding to this
/// deposit to the requested redemption output script. This will
/// move the deposit into a redeemed state.
/// @dev Takes a pre-parsed transaction and calculates values needed to
/// verify funding. Signers can have their bonds seized if this is not
/// called within `TBTCConstants.REDEMPTION_PROOF_TIMEOUT` seconds of
/// a redemption signature being provided.
/// @param _txVersion Transaction version number (4-byte little-endian).
/// @param _txInputVector All transaction inputs prepended by the number of
/// inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number
/// of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _merkleProof The merkle proof of transaction inclusion in a
/// block.
/// @param _txIndexInBlock Transaction index in the block (0-indexed).
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers,
/// lowest height first.
function provideRedemptionProof(
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public { // not external to allow bytes memory parameters
self.provideRedemptionProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
}
//--------------------------- MUTATING HELPERS -------------------------------//
/// @notice This function can only be called by the deposit factory; use
/// `DepositFactory.createDeposit` to create a new deposit.
/// @dev Initializes a new deposit clone with the base state for the
/// deposit.
/// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`.
/// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`.
/// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in
/// `TBTCDepositToken`.
/// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in
/// `FeeRebateToken`.
/// @param _vendingMachineAddress `VendingMachine` address. More info in
/// `VendingMachine`.
/// @param _lotSizeSatoshis The minimum amount of satoshi the funder is
/// required to send. This is also the amount of
/// TBTC the TDT holder will be eligible to mint:
/// (10**7 satoshi == 0.1 BTC == 0.1 TBTC).
function initializeDeposit(
ITBTCSystem _tbtcSystem,
TBTCToken _tbtcToken,
IERC721 _tbtcDepositToken,
FeeRebateToken _feeRebateToken,
address _vendingMachineAddress,
uint64 _lotSizeSatoshis
) public onlyFactory payable {
self.tbtcSystem = _tbtcSystem;
self.tbtcToken = _tbtcToken;
self.tbtcDepositToken = _tbtcDepositToken;
self.feeRebateToken = _feeRebateToken;
self.vendingMachineAddress = _vendingMachineAddress;
self.initialize(_lotSizeSatoshis);
}
/// @notice This function can only be called by the vending machine.
/// @dev Performs the same action as requestRedemption, but transfers
/// ownership of the deposit to the specified _finalRecipient. Used as
/// a utility helper for the vending machine's shortcut
/// TBTC->redemption path.
/// @param _outputValueBytes The 8-byte little-endian output size.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
/// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer.
function transferAndRequestRedemption(
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript,
address payable _finalRecipient
) public { // not external to allow bytes memory parameters
require(
msg.sender == self.vendingMachineAddress,
"Only the vending machine can call transferAndRequestRedemption"
);
self.transferAndRequestRedemption(
_outputValueBytes,
_redeemerOutputScript,
_finalRecipient
);
}
/// @notice Withdraw the ETH balance of the deposit allotted to the caller.
/// @dev Withdrawals can only happen when a contract is in an end-state.
function withdrawFunds() external {
self.withdrawFunds();
}
}
pragma solidity 0.5.17;
import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol";
import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol";
import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol";
import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import {DepositStates} from "./DepositStates.sol";
import {DepositUtils} from "./DepositUtils.sol";
import {TBTCConstants} from "../system/TBTCConstants.sol";
import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol";
library DepositLiquidation {
using BTCUtils for bytes;
using BytesLib for bytes;
using SafeMath for uint256;
using SafeMath for uint64;
using DepositUtils for DepositUtils.Deposit;
using DepositStates for DepositUtils.Deposit;
using OutsourceDepositLogging for DepositUtils.Deposit;
/// @notice Notifies the keep contract of fraud. Reverts if not fraud.
/// @dev Calls out to the keep contract. this could get expensive if preimage
/// is large.
/// @param _d Deposit storage pointer.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature vrs tuple.
/// @param _preimage The sha256 preimage of the digest.
function submitSignatureFraud(
DepositUtils.Deposit storage _d,
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public {
IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress);
_keep.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage);
}
/// @notice Determines the collateralization percentage of the signing group.
/// @dev Compares the bond value and lot value.
/// @param _d Deposit storage pointer.
/// @return Collateralization percentage as uint.
function collateralizationPercentage(DepositUtils.Deposit storage _d) public view returns (uint256) {
// Determine value of the lot in wei
uint256 _satoshiPrice = _d.fetchBitcoinPrice();
uint64 _lotSizeSatoshis = _d.lotSizeSatoshis;
uint256 _lotValue = _lotSizeSatoshis.mul(_satoshiPrice);
// Amount of wei the signers have
uint256 _bondValue = _d.fetchBondAmount();
// This converts into a percentage
return (_bondValue.mul(100).div(_lotValue));
}
/// @dev Starts signer liquidation by seizing signer bonds.
/// If the deposit is currently being redeemed, the redeemer
/// receives the full bond value; otherwise, a falling price auction
/// begins to buy 1 TBTC in exchange for a portion of the seized bonds;
/// see purchaseSignerBondsAtAuction().
/// @param _wasFraud True if liquidation is being started due to fraud, false if for any other reason.
/// @param _d Deposit storage pointer.
function startLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) internal {
_d.logStartedLiquidation(_wasFraud);
uint256 seized = _d.seizeSignerBonds();
address redeemerAddress = _d.redeemerAddress;
// Reclaim used state for gas savings
_d.redemptionTeardown();
// If we see fraud in the redemption flow, we shouldn't go to auction.
// Instead give the full signer bond directly to the redeemer.
if (_d.inRedemption() && _wasFraud) {
_d.setLiquidated();
_d.enableWithdrawal(redeemerAddress, seized);
_d.logLiquidated();
return;
}
_d.liquidationInitiator = msg.sender;
_d.liquidationInitiated = block.timestamp; // Store the timestamp for auction
if(_wasFraud){
_d.setFraudLiquidationInProgress();
}
else{
_d.setLiquidationInProgress();
}
}
/// @notice Anyone can provide a signature that was not requested to prove fraud.
/// @dev Calls out to the keep to verify if there was fraud.
/// @param _d Deposit storage pointer.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature vrs tuple.
/// @param _preimage The sha256 preimage of the digest.
function provideECDSAFraudProof(
DepositUtils.Deposit storage _d,
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public { // not external to allow bytes memory parameters
require(
!_d.inFunding(),
"Use provideFundingECDSAFraudProof instead"
);
require(
!_d.inSignerLiquidation(),
"Signer liquidation already in progress"
);
require(!_d.inEndState(), "Contract has halted");
submitSignatureFraud(_d, _v, _r, _s, _signedDigest, _preimage);
startLiquidation(_d, true);
}
/// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud.
/// @dev For interface, reading auctionValue will give a past value. the current is better.
/// @param _d Deposit storage pointer.
function purchaseSignerBondsAtAuction(DepositUtils.Deposit storage _d) external {
bool _wasFraud = _d.inFraudLiquidationInProgress();
require(_d.inSignerLiquidation(), "No active auction");
_d.setLiquidated();
_d.logLiquidated();
// Send the TBTC to the redeemer if they exist, otherwise to the TDT
// holder. If the TDT holder is the Vending Machine, burn it to maintain
// the peg. This is because, if there is a redeemer set here, the TDT
// holder has already been made whole at redemption request time.
address tbtcRecipient = _d.redeemerAddress;
if (tbtcRecipient == address(0)) {
tbtcRecipient = _d.depositOwner();
}
uint256 lotSizeTbtc = _d.lotSizeTbtc();
require(_d.tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt");
if(tbtcRecipient == _d.vendingMachineAddress){
_d.tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size
}
else{
_d.tbtcToken.transferFrom(msg.sender, tbtcRecipient, lotSizeTbtc);
}
// Distribute funds to auction buyer
uint256 valueToDistribute = _d.auctionValue();
_d.enableWithdrawal(msg.sender, valueToDistribute);
// Send any TBTC left to the Fee Rebate Token holder
_d.distributeFeeRebate();
// For fraud, pay remainder to the liquidation initiator.
// For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1,
// division will yield a 0 value which causes a revert; instead,
// we simply ignore such a tiny amount and leave some wei dust in escrow
uint256 contractEthBalance = address(this).balance;
address payable initiator = _d.liquidationInitiator;
if (initiator == address(0)){
initiator = address(0xdead);
}
if (contractEthBalance > valueToDistribute + 1) {
uint256 remainingUnallocated = contractEthBalance.sub(valueToDistribute);
if (_wasFraud) {
_d.enableWithdrawal(initiator, remainingUnallocated);
} else {
// There will always be a liquidation initiator.
uint256 split = remainingUnallocated.div(2);
_d.pushFundsToKeepGroup(split);
_d.enableWithdrawal(initiator, remainingUnallocated.sub(split));
}
}
}
/// @notice Notify the contract that the signers are undercollateralized.
/// @dev Calls out to the system for oracle info.
/// @param _d Deposit storage pointer.
function notifyCourtesyCall(DepositUtils.Deposit storage _d) external {
require(_d.inActive(), "Can only courtesy call from active state");
require(collateralizationPercentage(_d) < _d.undercollateralizedThresholdPercent, "Signers have sufficient collateral");
_d.courtesyCallInitiated = block.timestamp;
_d.setCourtesyCall();
_d.logCourtesyCalled();
}
/// @notice Goes from courtesy call to active.
/// @dev Only callable if collateral is sufficient and the deposit is not expiring.
/// @param _d Deposit storage pointer.
function exitCourtesyCall(DepositUtils.Deposit storage _d) external {
require(_d.inCourtesyCall(), "Not currently in courtesy call");
require(collateralizationPercentage(_d) >= _d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized");
_d.setActive();
_d.logExitedCourtesyCall();
}
/// @notice Notify the contract that the signers are undercollateralized.
/// @dev Calls out to the system for oracle info.
/// @param _d Deposit storage pointer.
function notifyUndercollateralizedLiquidation(DepositUtils.Deposit storage _d) external {
require(_d.inRedeemableState(), "Deposit not in active or courtesy call");
require(collateralizationPercentage(_d) < _d.severelyUndercollateralizedThresholdPercent, "Deposit has sufficient collateral");
startLiquidation(_d, false);
}
/// @notice Notifies the contract that the courtesy period has elapsed.
/// @dev This is treated as an abort, rather than fraud.
/// @param _d Deposit storage pointer.
function notifyCourtesyCallExpired(DepositUtils.Deposit storage _d) external {
require(_d.inCourtesyCall(), "Not in a courtesy call period");
require(block.timestamp >= _d.courtesyCallInitiated.add(TBTCConstants.getCourtesyCallTimeout()), "Courtesy period has not elapsed");
startLiquidation(_d, false);
}
}
pragma solidity ^0.5.10;
/** @title BitcoinSPV */
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
// The target at minimum Difficulty. Also the target of the genesis block
uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;
uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds
uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks
uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/* ***** */
/* UTILS */
/* ***** */
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _flag The first byte of a VarInt
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {
if (uint8(_flag[0]) == 0xff) {
return 8; // one-byte flag, 8 bytes data
}
if (uint8(_flag[0]) == 0xfe) {
return 4; // one-byte flag, 4 bytes data
}
if (uint8(_flag[0]) == 0xfd) {
return 2; // one-byte flag, 2 bytes data
}
return 0; // flag is data
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string starting with a VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {
uint8 _dataLen = determineVarIntDataLength(_b);
if (_dataLen == 0) {
return (0, uint8(_b[0]));
}
if (_b.length < 1 + _dataLen) {
return (ERR_BAD_ARG, 0);
}
uint256 _number = bytesToUint(reverseEndianness(_b.slice(1, _dataLen)));
return (_dataLen, _number);
}
/// @notice Changes the endianness of a byte array
/// @dev Returns a new, backwards, bytes
/// @param _b The bytes to reverse
/// @return The reversed bytes
function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {
bytes memory _newValue = new bytes(_b.length);
for (uint i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
/// @notice Changes the endianness of a uint256
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
/// @param _b The unsigned integer to reverse
/// @return The reversed value
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
/// @notice Converts big-endian bytes to a uint
/// @dev Traverses the byte array and sums the bytes
/// @param _b The big-endian bytes-encoded integer
/// @return The integer representation
function bytesToUint(bytes memory _b) internal pure returns (uint256) {
uint256 _number;
for (uint i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));
}
return _number;
}
/// @notice Get the last _num bytes from a byte array
/// @param _b The byte array to slice
/// @param _num The number of bytes to extract from the end
/// @return The last _num bytes of _b
function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {
uint256 _start = _b.length.sub(_num);
return _b.slice(_start, _num);
}
/// @notice Implements bitcoin's hash160 (rmd160(sha2()))
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash160(bytes memory _b) internal pure returns (bytes memory) {
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash256(bytes memory _b) internal pure returns (bytes32) {
return sha256(abi.encodePacked(sha256(_b)));
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The pre-image
/// @return The digest
function hash256View(bytes memory _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
let ptr := mload(0x40)
pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32))
pop(staticcall(gas, 2, ptr, 32, ptr, 32))
res := mload(ptr)
}
}
/* ************ */
/* Legacy Input */
/* ************ */
/// @notice Extracts the nth input from the vin (0-indexed)
/// @dev Iterates over the vin. If you need to extract several, write a custom function
/// @param _vin The vin as a tightly-packed byte array
/// @param _index The 0-indexed location of the input to extract
/// @return The input as a byte array
function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nIns, "Vin read overrun");
bytes memory _remaining;
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i ++) {
_remaining = _vin.slice(_offset, _vin.length - _offset);
_len = determineInputLength(_remaining);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
_offset = _offset + _len;
}
_remaining = _vin.slice(_offset, _vin.length - _offset);
_len = determineInputLength(_remaining);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _vin.slice(_offset, _len);
}
/// @notice Determines whether an input is legacy
/// @dev False if no scriptSig, otherwise True
/// @param _input The input
/// @return True for legacy, False for witness
function isLegacyInput(bytes memory _input) internal pure returns (bool) {
return _input.keccak256Slice(36, 1) != keccak256(hex"00");
}
/// @notice Determines the length of a scriptSig in an input
/// @dev Will return 0 if passed a witness input.
/// @param _input The LEGACY input
/// @return The length of the script sig
function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {
if (_input.length < 37) {
return (ERR_BAD_ARG, 0);
}
bytes memory _afterOutpoint = _input.slice(36, _input.length - 36);
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = parseVarInt(_afterOutpoint);
return (_varIntDataLen, _scriptSigLen);
}
/// @notice Determines the length of an input from its scriptSig
/// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence
/// @param _input The input
/// @return The length of the input in bytes
function determineInputLength(bytes memory _input) internal pure returns (uint256) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The LEGACY input
/// @return The sequence bytes (LE uint)
function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4);
}
/// @notice Extracts the sequence from the input
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The LEGACY input
/// @return The sequence number (big-endian uint)
function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {
bytes memory _leSeqence = extractSequenceLELegacy(_input);
bytes memory _beSequence = reverseEndianness(_leSeqence);
return uint32(bytesToUint(_beSequence));
}
/// @notice Extracts the VarInt-prepended scriptSig from the input in a tx
/// @dev Will return hex"00" if passed a witness input
/// @param _input The LEGACY input
/// @return The length-prepended scriptSig
function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);
}
/* ************* */
/* Witness Input */
/* ************* */
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The WITNESS input
/// @return The sequence bytes (LE uint)
function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(37, 4);
}
/// @notice Extracts the sequence from the input in a tx
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The WITNESS input
/// @return The sequence number (big-endian uint)
function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {
bytes memory _leSeqence = extractSequenceLEWitness(_input);
bytes memory _inputeSequence = reverseEndianness(_leSeqence);
return uint32(bytesToUint(_inputeSequence));
}
/// @notice Extracts the outpoint from the input in a tx
/// @dev 32-byte tx id with 4-byte index
/// @param _input The input
/// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)
function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(0, 36);
}
/// @notice Extracts the outpoint tx id from an input
/// @dev 32-byte tx id
/// @param _input The input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {
return _input.slice(0, 32).toBytes32();
}
/// @notice Extracts the LE tx input index from the input in a tx
/// @dev 4-byte tx index
/// @param _input The input
/// @return The tx index (little-endian bytes)
function extractTxIndexLE(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(32, 4);
}
/* ****** */
/* Output */
/* ****** */
/// @notice Determines the length of an output
/// @dev Works with any properly formatted output
/// @param _output The output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLength(bytes memory _output) internal pure returns (uint256) {
if (_output.length < 9) {
return ERR_BAD_ARG;
}
bytes memory _afterValue = _output.slice(8, _output.length - 8);
uint256 _varIntDataLen;
uint256 _scriptPubkeyLength;
(_varIntDataLen, _scriptPubkeyLength) = parseVarInt(_afterValue);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
// 8-byte value, 1-byte for tag itself
return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;
}
/// @notice Extracts the output at a given index in the TxOuts vector
/// @dev Iterates over the vout. If you need to extract multiple, write a custom function
/// @param _vout The _vout to extract from
/// @param _index The 0-indexed location of the output to extract
/// @return The specified output
function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nOuts, "Vout read overrun");
bytes memory _remaining;
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i ++) {
_remaining = _vout.slice(_offset, _vout.length - _offset);
_len = determineOutputLength(_remaining);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
_offset += _len;
}
_remaining = _vout.slice(_offset, _vout.length - _offset);
_len = determineOutputLength(_remaining);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
return _vout.slice(_offset, _len);
}
/// @notice Extracts the value bytes from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value as LE bytes
function extractValueLE(bytes memory _output) internal pure returns (bytes memory) {
return _output.slice(0, 8);
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value
function extractValue(bytes memory _output) internal pure returns (uint64) {
bytes memory _leValue = extractValueLE(_output);
bytes memory _beValue = reverseEndianness(_leValue);
return uint64(bytesToUint(_beValue));
}
/// @notice Extracts the data from an op return output
/// @dev Returns hex"" if no data or not an op return
/// @param _output The output
/// @return Any data contained in the opreturn output, null if not an op return
function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {
if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) {
return hex"";
}
bytes memory _dataLen = _output.slice(10, 1);
return _output.slice(11, bytesToUint(_dataLen));
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The output
/// @return The hash committed to by the pk_script, or null for errors
function extractHash(bytes memory _output) internal pure returns (bytes memory) {
uint8 _scriptLen = uint8(_output[8]);
// don't have to worry about overflow here.
// if _scriptLen + 9 overflows, then output.length would have to be < 9
// for this check to pass. if it's < 9, then we errored when assigning
// _scriptLen
if (_scriptLen + 9 != _output.length) {
return hex"";
}
if (uint8(_output[9]) == 0) {
if (_scriptLen < 2) {
return hex"";
}
uint256 _payloadLen = uint8(_output[10]);
// Check for maliciously formatted witness outputs.
// No need to worry about underflow as long b/c of the `< 2` check
if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {
return hex"";
}
return _output.slice(11, _payloadLen);
} else {
bytes32 _tag = _output.keccak256Slice(8, 3);
// p2pkh
if (_tag == keccak256(hex"1976a9")) {
// Check for maliciously formatted p2pkh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[11]) != 0x14 ||
_output.keccak256Slice(_output.length - 2, 2) != keccak256(hex"88ac")) {
return hex"";
}
return _output.slice(12, 20);
//p2sh
} else if (_tag == keccak256(hex"17a914")) {
// Check for maliciously formatted p2sh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[_output.length - 1]) != 0x87) {
return hex"";
}
return _output.slice(11, 20);
}
}
return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */
}
/* ********** */
/* Witness TX */
/* ********** */
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vin Raw bytes length-prefixed input vector
/// @return True if it represents a validly formatted vin
function validateVin(bytes memory _vin) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
// Not valid if it says there are too many or no inputs
if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nIns; i++) {
// If we're at the end, but still expect more
if (_offset >= _vin.length) {
return false;
}
// Grab the next input and determine its length.
bytes memory _next = _vin.slice(_offset, _vin.length - _offset);
uint256 _nextLen = determineInputLength(_next);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
// Increase the offset by that much
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vin.length;
}
/// @notice Checks that the vout passed up is properly formatted
/// @dev Consider a vout with a valid scriptpubkey
/// @param _vout Raw bytes length-prefixed output vector
/// @return True if it represents a validly formatted vout
function validateVout(bytes memory _vout) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
// Not valid if it says there are too many or no outputs
if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nOuts; i++) {
// If we're at the end, but still expect more
if (_offset >= _vout.length) {
return false;
}
// Grab the next output and determine its length.
// Increase the offset by that much
bytes memory _next = _vout.slice(_offset, _vout.length - _offset);
uint256 _nextLen = determineOutputLength(_next);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vout.length;
}
/* ************ */
/* Block Header */
/* ************ */
/// @notice Extracts the transaction merkle root from a block header
/// @dev Use verifyHash256Merkle to verify proofs with this root
/// @param _header The header
/// @return The merkle root (little-endian)
function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes memory) {
return _header.slice(36, 32);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _header The header
/// @return The target threshold
function extractTarget(bytes memory _header) internal pure returns (uint256) {
bytes memory _m = _header.slice(72, 3);
uint8 _e = uint8(_header[75]);
uint256 _mantissa = bytesToUint(reverseEndianness(_m));
uint _exponent = _e - 3;
return _mantissa * (256 ** _exponent);
}
/// @notice Calculate difficulty from the difficulty 1 target and current target
/// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet
/// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _target The current target
/// @return The block difficulty (bdiff)
function calculateDifficulty(uint256 _target) internal pure returns (uint256) {
// Difficulty 1 calculated from 0x1d00ffff
return DIFF1_TARGET.div(_target);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) {
return _header.slice(4, 32);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (little-endian bytes)
function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) {
return _header.slice(68, 4);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (uint)
function extractTimestamp(bytes memory _header) internal pure returns (uint32) {
return uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header))));
}
/// @notice Extracts the expected difficulty from a block header
/// @dev Does NOT verify the work
/// @param _header The header
/// @return The difficulty as an integer
function extractDifficulty(bytes memory _header) internal pure returns (uint256) {
return calculateDifficulty(extractTarget(_header));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal pure returns (bytes32) {
return hash256(abi.encodePacked(_a, _b));
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed.
/// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes memory _proof, uint _index) internal pure returns (bool) {
// Not an even number of hashes
if (_proof.length % 32 != 0) {
return false;
}
// Special case for coinbase-only blocks
if (_proof.length == 32) {
return true;
}
// Should never occur
if (_proof.length == 64) {
return false;
}
uint _idx = _index;
bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32();
bytes32 _current = _proof.slice(0, 32).toBytes32();
for (uint i = 1; i < (_proof.length.div(32)) - 1; i++) {
if (_idx % 2 == 1) {
_current = _hash256MerkleStep(_proof.slice(i * 32, 32), abi.encodePacked(_current));
} else {
_current = _hash256MerkleStep(abi.encodePacked(_current), _proof.slice(i * 32, 32));
}
_idx = _idx >> 1;
}
return _current == _root;
}
/*
NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72
NB: We get a full-bitlength target from this. For comparison with
header-encoded targets we need to mask it with the header target
e.g. (full & truncated) == truncated
*/
/// @notice performs the bitcoin difficulty retarget
/// @dev implements the Bitcoin algorithm precisely
/// @param _previousTarget the target of the previous period
/// @param _firstTimestamp the timestamp of the first block in the difficulty period
/// @param _secondTimestamp the timestamp of the last block in the difficulty period
/// @return the new period's target threshold
function retargetAlgorithm(
uint256 _previousTarget,
uint256 _firstTimestamp,
uint256 _secondTimestamp
) internal pure returns (uint256) {
uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);
// Normalize ratio to factor of 4 if very long or very short
if (_elapsedTime < RETARGET_PERIOD.div(4)) {
_elapsedTime = RETARGET_PERIOD.div(4);
}
if (_elapsedTime > RETARGET_PERIOD.mul(4)) {
_elapsedTime = RETARGET_PERIOD.mul(4);
}
/*
NB: high targets e.g. ffff0020 can cause overflows here
so we divide it by 256**2, then multiply by 256**2 later
we know the target is evenly divisible by 256**2, so this isn't an issue
*/
uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);
return _adjusted.div(RETARGET_PERIOD).mul(65536);
}
}
pragma solidity ^0.5.10;
/*
https://github.com/GNSPS/solidity-bytes-utils/
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*/
/** @title BytesLib **/
/** @author https://github.com/GNSPS **/
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {
if (_length == 0) {
return hex"";
}
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
// Alloc bytes array with additional 32 bytes afterspace and assign it's size
res := mload(0x40)
mstore(0x40, add(add(res, 64), _length))
mstore(res, _length)
// Compute distance between source and destination pointers
let diff := sub(res, add(_bytes, _start))
for {
let src := add(add(_bytes, 32), _start)
let end := add(src, _length)
} lt(src, end) {
src := add(src, 32)
} {
mstore(add(src, diff), mload(src))
}
}
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
uint _totalLen = _start + 20;
require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
uint _totalLen = _start + 32;
require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {
if (_source.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
result := keccak256(add(add(_bytes, 32), _start), _length)
}
}
}
pragma solidity ^0.5.10;
/*
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
require(c / _a == _b, "Overflow during multiplication.");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, "Underflow during subtraction.");
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
require(c >= _a, "Overflow during addition.");
return c;
}
}
pragma solidity 0.5.17;
import {DepositUtils} from "./DepositUtils.sol";
library DepositStates {
enum States {
// DOES NOT EXIST YET
START,
// FUNDING FLOW
AWAITING_SIGNER_SETUP,
AWAITING_BTC_FUNDING_PROOF,
// FAILED SETUP
FAILED_SETUP,
// ACTIVE
ACTIVE, // includes courtesy call
// REDEMPTION FLOW
AWAITING_WITHDRAWAL_SIGNATURE,
AWAITING_WITHDRAWAL_PROOF,
REDEEMED,
// SIGNER LIQUIDATION FLOW
COURTESY_CALL,
FRAUD_LIQUIDATION_IN_PROGRESS,
LIQUIDATION_IN_PROGRESS,
LIQUIDATED
}
/// @notice Check if the contract is currently in the funding flow.
/// @dev This checks on the funding flow happy path, not the fraud path.
/// @param _d Deposit storage pointer.
/// @return True if contract is currently in the funding flow else False.
function inFunding(DepositUtils.Deposit storage _d) public view returns (bool) {
return (
_d.currentState == uint8(States.AWAITING_SIGNER_SETUP)
|| _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF)
);
}
/// @notice Check if the contract is currently in the signer liquidation flow.
/// @dev This could be caused by fraud, or by an unfilled margin call.
/// @param _d Deposit storage pointer.
/// @return True if contract is currently in the liquidaton flow else False.
function inSignerLiquidation(DepositUtils.Deposit storage _d) public view returns (bool) {
return (
_d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS)
|| _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS)
);
}
/// @notice Check if the contract is currently in the redepmtion flow.
/// @dev This checks on the redemption flow, not the REDEEMED termination state.
/// @param _d Deposit storage pointer.
/// @return True if contract is currently in the redemption flow else False.
function inRedemption(DepositUtils.Deposit storage _d) public view returns (bool) {
return (
_d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE)
|| _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF)
);
}
/// @notice Check if the contract has halted.
/// @dev This checks on any halt state, regardless of triggering circumstances.
/// @param _d Deposit storage pointer.
/// @return True if contract has halted permanently.
function inEndState(DepositUtils.Deposit storage _d) public view returns (bool) {
return (
_d.currentState == uint8(States.LIQUIDATED)
|| _d.currentState == uint8(States.REDEEMED)
|| _d.currentState == uint8(States.FAILED_SETUP)
);
}
/// @notice Check if the contract is available for a redemption request.
/// @dev Redemption is available from active and courtesy call.
/// @param _d Deposit storage pointer.
/// @return True if available, False otherwise.
function inRedeemableState(DepositUtils.Deposit storage _d) public view returns (bool) {
return (
_d.currentState == uint8(States.ACTIVE)
|| _d.currentState == uint8(States.COURTESY_CALL)
);
}
/// @notice Check if the contract is currently in the start state (awaiting setup).
/// @dev This checks on the funding flow happy path, not the fraud path.
/// @param _d Deposit storage pointer.
/// @return True if contract is currently in the start state else False.
function inStart(DepositUtils.Deposit storage _d) public view returns (bool) {
return (_d.currentState == uint8(States.START));
}
function inAwaitingSignerSetup(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.AWAITING_SIGNER_SETUP);
}
function inAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF);
}
function inFailedSetup(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.FAILED_SETUP);
}
function inActive(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.ACTIVE);
}
function inAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE);
}
function inAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF);
}
function inRedeemed(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.REDEEMED);
}
function inCourtesyCall(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.COURTESY_CALL);
}
function inFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS);
}
function inLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS);
}
function inLiquidated(DepositUtils.Deposit storage _d) external view returns (bool) {
return _d.currentState == uint8(States.LIQUIDATED);
}
function setAwaitingSignerSetup(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.AWAITING_SIGNER_SETUP);
}
function setAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.AWAITING_BTC_FUNDING_PROOF);
}
function setFailedSetup(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.FAILED_SETUP);
}
function setActive(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.ACTIVE);
}
function setAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.AWAITING_WITHDRAWAL_SIGNATURE);
}
function setAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.AWAITING_WITHDRAWAL_PROOF);
}
function setRedeemed(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.REDEEMED);
}
function setCourtesyCall(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.COURTESY_CALL);
}
function setFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS);
}
function setLiquidationInProgress(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.LIQUIDATION_IN_PROGRESS);
}
function setLiquidated(DepositUtils.Deposit storage _d) external {
_d.currentState = uint8(States.LIQUIDATED);
}
}
pragma solidity 0.5.17;
import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol";
import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol";
import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol";
import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol";
import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";
import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import {DepositStates} from "./DepositStates.sol";
import {TBTCConstants} from "../system/TBTCConstants.sol";
import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {FeeRebateToken} from "../system/FeeRebateToken.sol";
library DepositUtils {
using SafeMath for uint256;
using SafeMath for uint64;
using BytesLib for bytes;
using BTCUtils for bytes;
using BTCUtils for uint256;
using ValidateSPV for bytes;
using ValidateSPV for bytes32;
using DepositStates for DepositUtils.Deposit;
struct Deposit {
// SET DURING CONSTRUCTION
ITBTCSystem tbtcSystem;
TBTCToken tbtcToken;
IERC721 tbtcDepositToken;
FeeRebateToken feeRebateToken;
address vendingMachineAddress;
uint64 lotSizeSatoshis;
uint8 currentState;
uint16 signerFeeDivisor;
uint16 initialCollateralizedPercent;
uint16 undercollateralizedThresholdPercent;
uint16 severelyUndercollateralizedThresholdPercent;
uint256 keepSetupFee;
// SET ON FRAUD
uint256 liquidationInitiated; // Timestamp of when liquidation starts
uint256 courtesyCallInitiated; // When the courtesy call is issued
address payable liquidationInitiator;
// written when we request a keep
address keepAddress; // The address of our keep contract
uint256 signingGroupRequestedAt; // timestamp of signing group request
// written when we get a keep result
uint256 fundingProofTimerStart; // start of the funding proof period. reused for funding fraud proof period
bytes32 signingGroupPubkeyX; // The X coordinate of the signing group's pubkey
bytes32 signingGroupPubkeyY; // The Y coordinate of the signing group's pubkey
// INITIALLY WRITTEN BY REDEMPTION FLOW
address payable redeemerAddress; // The redeemer's address, used as fallback for fraud in redemption
bytes redeemerOutputScript; // The redeemer output script
uint256 initialRedemptionFee; // the initial fee as requested
uint256 latestRedemptionFee; // the fee currently required by a redemption transaction
uint256 withdrawalRequestTime; // the most recent withdrawal request timestamp
bytes32 lastRequestedDigest; // the digest most recently requested for signing
// written when we get funded
bytes8 utxoValueBytes; // LE uint. the size of the deposit UTXO in satoshis
uint256 fundedAt; // timestamp when funding proof was received
bytes utxoOutpoint; // the 36-byte outpoint of the custodied UTXO
/// @dev Map of ETH balances an address can withdraw after contract reaches ends-state.
mapping(address => uint256) withdrawableAmounts;
/// @dev Map of timestamps representing when transaction digests were approved for signing
mapping (bytes32 => uint256) approvedDigests;
}
/// @notice Closes keep associated with the deposit.
/// @dev Should be called when the keep is no longer needed and the signing
/// group can disband.
function closeKeep(DepositUtils.Deposit storage _d) internal {
IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress);
_keep.closeKeep();
}
/// @notice Gets the current block difficulty.
/// @dev Calls the light relay and gets the current block difficulty.
/// @return The difficulty.
function currentBlockDifficulty(Deposit storage _d) public view returns (uint256) {
return _d.tbtcSystem.fetchRelayCurrentDifficulty();
}
/// @notice Gets the previous block difficulty.
/// @dev Calls the light relay and gets the previous block difficulty.
/// @return The difficulty.
function previousBlockDifficulty(Deposit storage _d) public view returns (uint256) {
return _d.tbtcSystem.fetchRelayPreviousDifficulty();
}
/// @notice Evaluates the header difficulties in a proof.
/// @dev Uses the light oracle to source recent difficulty.
/// @param _bitcoinHeaders The header chain to evaluate.
/// @return True if acceptable, otherwise revert.
function evaluateProofDifficulty(Deposit storage _d, bytes memory _bitcoinHeaders) public view {
uint256 _reqDiff;
uint256 _current = currentBlockDifficulty(_d);
uint256 _previous = previousBlockDifficulty(_d);
uint256 _firstHeaderDiff = _bitcoinHeaders.extractTarget().calculateDifficulty();
if (_firstHeaderDiff == _current) {
_reqDiff = _current;
} else if (_firstHeaderDiff == _previous) {
_reqDiff = _previous;
} else {
revert("not at current or previous difficulty");
}
uint256 _observedDiff = _bitcoinHeaders.validateHeaderChain();
require(_observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain");
require(_observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain");
require(_observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header");
require(
_observedDiff >= _reqDiff.mul(TBTCConstants.getTxProofDifficultyFactor()),
"Insufficient accumulated difficulty in header chain"
);
}
/// @notice Syntactically check an SPV proof for a bitcoin transaction with its hash (ID).
/// @dev Stateless SPV Proof verification documented elsewhere (see https://github.com/summa-tx/bitcoin-spv).
/// @param _d Deposit storage pointer.
/// @param _txId The bitcoin txid of the tx that is purportedly included in the header chain.
/// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block.
/// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed).
/// @param _bitcoinHeaders An array of tightly-packed bitcoin headers.
function checkProofFromTxId(
Deposit storage _d,
bytes32 _txId,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public view{
require(
_txId.prove(
_bitcoinHeaders.extractMerkleRootLE().toBytes32(),
_merkleProof,
_txIndexInBlock
),
"Tx merkle proof is not valid for provided header and txId");
evaluateProofDifficulty(_d, _bitcoinHeaders);
}
/// @notice Find and validate funding output in transaction output vector using the index.
/// @dev Gets `_fundingOutputIndex` output from the output vector and validates if it is
/// a p2wpkh output with public key hash matching this deposit's public key hash.
/// @param _d Deposit storage pointer.
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC outputs.
/// @param _fundingOutputIndex Index of funding output in _txOutputVector.
/// @return Funding value.
function findAndParseFundingOutput(
DepositUtils.Deposit storage _d,
bytes memory _txOutputVector,
uint8 _fundingOutputIndex
) public view returns (bytes8) {
bytes8 _valueBytes;
bytes memory _output;
// Find the output paying the signer PKH
_output = _txOutputVector.extractOutputAtIndex(_fundingOutputIndex);
require(
keccak256(_output.extractHash()) == keccak256(abi.encodePacked(signerPKH(_d))),
"Could not identify output funding the required public key hash"
);
require(
_output.length == 31 &&
_output.keccak256Slice(8, 23) == keccak256(abi.encodePacked(hex"160014", signerPKH(_d))),
"Funding transaction output type unsupported: only p2wpkh outputs are supported"
);
_valueBytes = bytes8(_output.slice(0, 8).toBytes32());
return _valueBytes;
}
/// @notice Validates the funding tx and parses information from it.
/// @dev Takes a pre-parsed transaction and calculates values needed to verify funding.
/// @param _d Deposit storage pointer.
/// @param _txVersion Transaction version number (4-byte LE).
/// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed).
/// @param _merkleProof The merkle proof of transaction inclusion in a block.
/// @param _txIndexInBlock Transaction index in the block (0-indexed).
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first.
/// @return The 8-byte LE UTXO size in satoshi, the 36byte outpoint.
function validateAndParseFundingSPVProof(
DepositUtils.Deposit storage _d,
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public view returns (bytes8 _valueBytes, bytes memory _utxoOutpoint){ // not external to allow bytes memory parameters
require(_txInputVector.validateVin(), "invalid input vector provided");
require(_txOutputVector.validateVout(), "invalid output vector provided");
bytes32 txID = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256();
_valueBytes = findAndParseFundingOutput(_d, _txOutputVector, _fundingOutputIndex);
require(bytes8LEToUint(_valueBytes) >= _d.lotSizeSatoshis, "Deposit too small");
checkProofFromTxId(_d, txID, _merkleProof, _txIndexInBlock, _bitcoinHeaders);
// The utxoOutpoint is the LE txID plus the index of the output as a 4-byte LE int
// _fundingOutputIndex is a uint8, so we know it is only 1 byte
// Therefore, pad with 3 more bytes
_utxoOutpoint = abi.encodePacked(txID, _fundingOutputIndex, hex"000000");
}
/// @notice Retreive the remaining term of the deposit
/// @dev The return value is not guaranteed since block.timestmap can be lightly manipulated by miners.
/// @return The remaining term of the deposit in seconds. 0 if already at term
function remainingTerm(DepositUtils.Deposit storage _d) public view returns(uint256){
uint256 endOfTerm = _d.fundedAt.add(TBTCConstants.getDepositTerm());
if(block.timestamp < endOfTerm ) {
return endOfTerm.sub(block.timestamp);
}
return 0;
}
/// @notice Calculates the amount of value at auction right now.
/// @dev We calculate the % of the auction that has elapsed, then scale the value up.
/// @param _d Deposit storage pointer.
/// @return The value in wei to distribute in the auction at the current time.
function auctionValue(Deposit storage _d) external view returns (uint256) {
uint256 _elapsed = block.timestamp.sub(_d.liquidationInitiated);
uint256 _available = address(this).balance;
if (_elapsed > TBTCConstants.getAuctionDuration()) {
return _available;
}
// This should make a smooth flow from base% to 100%
uint256 _basePercentage = getAuctionBasePercentage(_d);
uint256 _elapsedPercentage = uint256(100).sub(_basePercentage).mul(_elapsed).div(TBTCConstants.getAuctionDuration());
uint256 _percentage = _basePercentage.add(_elapsedPercentage);
return _available.mul(_percentage).div(100);
}
/// @notice Gets the lot size in erc20 decimal places (max 18)
/// @return uint256 lot size in 10**18 decimals.
function lotSizeTbtc(Deposit storage _d) public view returns (uint256){
return _d.lotSizeSatoshis.mul(TBTCConstants.getSatoshiMultiplier());
}
/// @notice Determines the fees due to the signers for work performed.
/// @dev Signers are paid based on the TBTC issued.
/// @return Accumulated fees in 10**18 decimals.
function signerFeeTbtc(Deposit storage _d) public view returns (uint256) {
return lotSizeTbtc(_d).div(_d.signerFeeDivisor);
}
/// @notice Determines the prefix to the compressed public key.
/// @dev The prefix encodes the parity of the Y coordinate.
/// @param _pubkeyY The Y coordinate of the public key.
/// @return The 1-byte prefix for the compressed key.
function determineCompressionPrefix(bytes32 _pubkeyY) public pure returns (bytes memory) {
if(uint256(_pubkeyY) & 1 == 1) {
return hex"03"; // Odd Y
} else {
return hex"02"; // Even Y
}
}
/// @notice Compresses a public key.
/// @dev Converts the 64-byte key to a 33-byte key, bitcoin-style.
/// @param _pubkeyX The X coordinate of the public key.
/// @param _pubkeyY The Y coordinate of the public key.
/// @return The 33-byte compressed pubkey.
function compressPubkey(bytes32 _pubkeyX, bytes32 _pubkeyY) public pure returns (bytes memory) {
return abi.encodePacked(determineCompressionPrefix(_pubkeyY), _pubkeyX);
}
/// @notice Returns the packed public key (64 bytes) for the signing group.
/// @dev We store it as 2 bytes32, (2 slots) then repack it on demand.
/// @return 64 byte public key.
function signerPubkey(Deposit storage _d) external view returns (bytes memory) {
return abi.encodePacked(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY);
}
/// @notice Returns the Bitcoin pubkeyhash (hash160) for the signing group.
/// @dev This is used in bitcoin output scripts for the signers.
/// @return 20-bytes public key hash.
function signerPKH(Deposit storage _d) public view returns (bytes20) {
bytes memory _pubkey = compressPubkey(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY);
bytes memory _digest = _pubkey.hash160();
return bytes20(_digest.toAddress(0)); // dirty solidity hack
}
/// @notice Returns the size of the deposit UTXO in satoshi.
/// @dev We store the deposit as bytes8 to make signature checking easier.
/// @return UTXO value in satoshi.
function utxoValue(Deposit storage _d) external view returns (uint256) {
return bytes8LEToUint(_d.utxoValueBytes);
}
/// @notice Gets the current price of Bitcoin in Ether.
/// @dev Polls the price feed via the system contract.
/// @return The current price of 1 sat in wei.
function fetchBitcoinPrice(Deposit storage _d) external view returns (uint256) {
return _d.tbtcSystem.fetchBitcoinPrice();
}
/// @notice Fetches the Keep's bond amount in wei.
/// @dev Calls the keep contract to do so.
/// @return The amount of bonded ETH in wei.
function fetchBondAmount(Deposit storage _d) external view returns (uint256) {
IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress);
return _keep.checkBondAmount();
}
/// @notice Convert a LE bytes8 to a uint256.
/// @dev Do this by converting to bytes, then reversing endianness, then converting to int.
/// @return The uint256 represented in LE by the bytes8.
function bytes8LEToUint(bytes8 _b) public pure returns (uint256) {
return abi.encodePacked(_b).reverseEndianness().bytesToUint();
}
/// @notice Gets timestamp of digest approval for signing.
/// @dev Identifies entry in the recorded approvals by keep ID and digest pair.
/// @param _digest Digest to check approval for.
/// @return Timestamp from the moment of recording the digest for signing.
/// Returns 0 if the digest was not approved for signing.
function wasDigestApprovedForSigning(Deposit storage _d, bytes32 _digest) external view returns (uint256) {
return _d.approvedDigests[_digest];
}
/// @notice Looks up the Fee Rebate Token holder.
/// @return The current token holder if the Token exists.
/// address(0) if the token does not exist.
function feeRebateTokenHolder(Deposit storage _d) public view returns (address payable) {
address tokenHolder = address(0);
if(_d.feeRebateToken.exists(uint256(address(this)))){
tokenHolder = address(uint160(_d.feeRebateToken.ownerOf(uint256(address(this)))));
}
return address(uint160(tokenHolder));
}
/// @notice Looks up the deposit beneficiary by calling the tBTC system.
/// @dev We cast the address to a uint256 to match the 721 standard.
/// @return The current deposit beneficiary.
function depositOwner(Deposit storage _d) public view returns (address payable) {
return address(uint160(_d.tbtcDepositToken.ownerOf(uint256(address(this)))));
}
/// @notice Deletes state after termination of redemption process.
/// @dev We keep around the redeemer address so we can pay them out.
function redemptionTeardown(Deposit storage _d) public {
_d.redeemerOutputScript = "";
_d.initialRedemptionFee = 0;
_d.withdrawalRequestTime = 0;
_d.lastRequestedDigest = bytes32(0);
}
/// @notice Get the starting percentage of the bond at auction.
/// @dev This will return the same value regardless of collateral price.
/// @return The percentage of the InitialCollateralizationPercent that will result
/// in a 100% bond value base auction given perfect collateralization.
function getAuctionBasePercentage(Deposit storage _d) internal view returns (uint256) {
return uint256(10000).div(_d.initialCollateralizedPercent);
}
/// @notice Seize the signer bond from the keep contract.
/// @dev we check our balance before and after.
/// @return The amount seized in wei.
function seizeSignerBonds(Deposit storage _d) internal returns (uint256) {
uint256 _preCallBalance = address(this).balance;
IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress);
_keep.seizeSignerBonds();
uint256 _postCallBalance = address(this).balance;
require(_postCallBalance > _preCallBalance, "No funds received, unexpected");
return _postCallBalance.sub(_preCallBalance);
}
/// @notice Adds a given amount to the withdraw allowance for the address.
/// @dev Withdrawals can only happen when a contract is in an end-state.
function enableWithdrawal(DepositUtils.Deposit storage _d, address _withdrawer, uint256 _amount) internal {
_d.withdrawableAmounts[_withdrawer] = _d.withdrawableAmounts[_withdrawer].add(_amount);
}
/// @notice Withdraw caller's allowance.
/// @dev Withdrawals can only happen when a contract is in an end-state.
function withdrawFunds(DepositUtils.Deposit storage _d) internal {
uint256 available = _d.withdrawableAmounts[msg.sender];
require(_d.inEndState(), "Contract not yet terminated");
require(available > 0, "Nothing to withdraw");
require(address(this).balance >= available, "Insufficient contract balance");
// zero-out to prevent reentrancy
_d.withdrawableAmounts[msg.sender] = 0;
/* solium-disable-next-line security/no-call-value */
(bool ok,) = msg.sender.call.value(available)("");
require(
ok,
"Failed to send withdrawable amount to sender"
);
}
/// @notice Get the caller's withdraw allowance.
/// @return The caller's withdraw allowance in wei.
function getWithdrawableAmount(DepositUtils.Deposit storage _d) internal view returns (uint256) {
return _d.withdrawableAmounts[msg.sender];
}
/// @notice Distributes the fee rebate to the Fee Rebate Token owner.
/// @dev Whenever this is called we are shutting down.
function distributeFeeRebate(Deposit storage _d) internal {
address rebateTokenHolder = feeRebateTokenHolder(_d);
// exit the function if there is nobody to send the rebate to
if(rebateTokenHolder == address(0)){
return;
}
// pay out the rebate if it is available
if(_d.tbtcToken.balanceOf(address(this)) >= signerFeeTbtc(_d)) {
_d.tbtcToken.transfer(rebateTokenHolder, signerFeeTbtc(_d));
}
}
/// @notice Pushes ether held by the deposit to the signer group.
/// @dev Ether is returned to signing group members bonds.
/// @param _ethValue The amount of ether to send.
function pushFundsToKeepGroup(Deposit storage _d, uint256 _ethValue) internal {
require(address(this).balance >= _ethValue, "Not enough funds to send");
if(_ethValue > 0){
IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress);
_keep.returnPartialSignerBonds.value(_ethValue)();
}
}
/// @notice Calculate TBTC amount required for redemption by a specified
/// _redeemer. If _assumeRedeemerHoldTdt is true, return the
/// requirement as if the redeemer holds this deposit's TDT.
/// @dev Will revert if redemption is not possible by the current owner and
/// _assumeRedeemerHoldsTdt was not set. Setting
/// _assumeRedeemerHoldsTdt only when appropriate is the responsibility
/// of the caller; as such, this function should NEVER be publicly
/// exposed.
/// @param _redeemer The account that should be treated as redeeming this
/// deposit for the purposes of this calculation.
/// @param _assumeRedeemerHoldsTdt If true, the calculation assumes that the
/// specified redeemer holds the TDT. If false, the calculation
/// checks the deposit owner against the specified _redeemer. Note
/// that this parameter should be false for all mutating calls to
/// preserve system correctness.
/// @return A tuple of the amount the redeemer owes to the deposit to
/// initiate redemption, the amount that is owed to the TDT holder
/// when redemption is initiated, and the amount that is owed to the
/// FRT holder when redemption is initiated.
function calculateRedemptionTbtcAmounts(
DepositUtils.Deposit storage _d,
address _redeemer,
bool _assumeRedeemerHoldsTdt
) internal view returns (
uint256 owedToDeposit,
uint256 owedToTdtHolder,
uint256 owedToFrtHolder
) {
bool redeemerHoldsTdt =
_assumeRedeemerHoldsTdt || depositOwner(_d) == _redeemer;
bool preTerm = remainingTerm(_d) > 0 && !_d.inCourtesyCall();
require(
redeemerHoldsTdt || !preTerm,
"Only TDT holder can redeem unless deposit is at-term or in COURTESY_CALL"
);
bool frtExists = feeRebateTokenHolder(_d) != address(0);
bool redeemerHoldsFrt = feeRebateTokenHolder(_d) == _redeemer;
uint256 signerFee = signerFeeTbtc(_d);
uint256 feeEscrow = calculateRedemptionFeeEscrow(
signerFee,
preTerm,
frtExists,
redeemerHoldsTdt,
redeemerHoldsFrt
);
// Base redemption + fee = total we need to have escrowed to start
// redemption.
owedToDeposit =
calculateBaseRedemptionCharge(
lotSizeTbtc(_d),
redeemerHoldsTdt
).add(feeEscrow);
// Adjust the amount owed to the deposit based on any balance the
// deposit already has.
uint256 balance = _d.tbtcToken.balanceOf(address(this));
if (owedToDeposit > balance) {
owedToDeposit = owedToDeposit.sub(balance);
} else {
owedToDeposit = 0;
}
// Pre-term, the FRT rebate is payed out, but if the redeemer holds the
// FRT, the amount has already been subtracted from what is owed to the
// deposit at this point (by calculateRedemptionFeeEscrow). This allows
// the redeemer to simply *not pay* the fee rebate, rather than having
// them pay it only to have it immediately returned.
if (preTerm && frtExists && !redeemerHoldsFrt) {
owedToFrtHolder = signerFee;
}
// The TDT holder gets any leftover balance.
owedToTdtHolder =
balance.add(owedToDeposit).sub(signerFee).sub(owedToFrtHolder);
return (owedToDeposit, owedToTdtHolder, owedToFrtHolder);
}
/// @notice Get the base TBTC amount needed to redeem.
/// @param _lotSize The lot size to use for the base redemption charge.
/// @param _redeemerHoldsTdt True if the redeemer is the TDT holder.
/// @return The amount in TBTC.
function calculateBaseRedemptionCharge(
uint256 _lotSize,
bool _redeemerHoldsTdt
) internal pure returns (uint256){
if (_redeemerHoldsTdt) {
return 0;
}
return _lotSize;
}
/// @notice Get fees owed for redemption
/// @param signerFee The value of the signer fee for fee calculations.
/// @param _preTerm True if the Deposit is at-term or in courtesy_call.
/// @param _frtExists True if the FRT exists.
/// @param _redeemerHoldsTdt True if the the redeemer holds the TDT.
/// @param _redeemerHoldsFrt True if the redeemer holds the FRT.
/// @return The fees owed in TBTC.
function calculateRedemptionFeeEscrow(
uint256 signerFee,
bool _preTerm,
bool _frtExists,
bool _redeemerHoldsTdt,
bool _redeemerHoldsFrt
) internal pure returns (uint256) {
// Escrow the fee rebate so the FRT holder can be repaids, unless the
// redeemer holds the FRT, in which case we simply don't require the
// rebate from them.
bool escrowRequiresFeeRebate =
_preTerm && _frtExists && ! _redeemerHoldsFrt;
bool escrowRequiresFee =
_preTerm ||
// If the FRT exists at term/courtesy call, the fee is
// "required", but should already be escrowed before redemption.
_frtExists ||
// The TDT holder always owes fees if there is no FRT.
_redeemerHoldsTdt;
uint256 feeEscrow = 0;
if (escrowRequiresFee) {
feeEscrow += signerFee;
}
if (escrowRequiresFeeRebate) {
feeEscrow += signerFee;
}
return feeEscrow;
}
}
pragma solidity 0.5.17;
import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol";
import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol";
import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol";
import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {DepositUtils} from "./DepositUtils.sol";
import {DepositLiquidation} from "./DepositLiquidation.sol";
import {DepositStates} from "./DepositStates.sol";
import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol";
import {TBTCConstants} from "../system/TBTCConstants.sol";
library DepositFunding {
using SafeMath for uint256;
using SafeMath for uint64;
using BTCUtils for bytes;
using BytesLib for bytes;
using DepositUtils for DepositUtils.Deposit;
using DepositStates for DepositUtils.Deposit;
using DepositLiquidation for DepositUtils.Deposit;
using OutsourceDepositLogging for DepositUtils.Deposit;
/// @notice Deletes state after funding.
/// @dev This is called when we go to ACTIVE or setup fails without fraud.
function fundingTeardown(DepositUtils.Deposit storage _d) internal {
_d.signingGroupRequestedAt = 0;
_d.fundingProofTimerStart = 0;
}
/// @notice Deletes state after the funding ECDSA fraud process.
/// @dev This is only called as we transition to setup failed.
function fundingFraudTeardown(DepositUtils.Deposit storage _d) internal {
_d.keepAddress = address(0);
_d.signingGroupRequestedAt = 0;
_d.fundingProofTimerStart = 0;
_d.signingGroupPubkeyX = bytes32(0);
_d.signingGroupPubkeyY = bytes32(0);
}
/// @notice Internally called function to set up a newly created Deposit
/// instance. This should not be called by developers, use
/// `DepositFactory.createDeposit` to create a new deposit.
/// @dev If called directly, the transaction will revert since the call will
/// be executed on an already set-up instance.
/// @param _d Deposit storage pointer.
/// @param _lotSizeSatoshis Lot size in satoshis.
function initialize(
DepositUtils.Deposit storage _d,
uint64 _lotSizeSatoshis
) public {
require(_d.tbtcSystem.getAllowNewDeposits(), "New deposits aren't allowed.");
require(_d.inStart(), "Deposit setup already requested");
_d.lotSizeSatoshis = _lotSizeSatoshis;
_d.keepSetupFee = _d.tbtcSystem.getNewDepositFeeEstimate();
// Note: this is a library, and library functions cannot be marked as
// payable. Thus, we disable Solium's check that msg.value can only be
// used in a payable function---this restriction actually applies to the
// caller of this `initialize` function, Deposit.initializeDeposit.
/* solium-disable-next-line value-in-payable */
_d.keepAddress = _d.tbtcSystem.requestNewKeep.value(msg.value)(
_lotSizeSatoshis,
TBTCConstants.getDepositTerm()
);
require(_d.fetchBondAmount() >= _d.keepSetupFee, "Insufficient signer bonds to cover setup fee");
_d.signerFeeDivisor = _d.tbtcSystem.getSignerFeeDivisor();
_d.undercollateralizedThresholdPercent = _d.tbtcSystem.getUndercollateralizedThresholdPercent();
_d.severelyUndercollateralizedThresholdPercent = _d.tbtcSystem.getSeverelyUndercollateralizedThresholdPercent();
_d.initialCollateralizedPercent = _d.tbtcSystem.getInitialCollateralizedPercent();
_d.signingGroupRequestedAt = block.timestamp;
_d.setAwaitingSignerSetup();
_d.logCreated(_d.keepAddress);
}
/// @notice Anyone may notify the contract that signing group setup has timed out.
/// @param _d Deposit storage pointer.
function notifySignerSetupFailed(DepositUtils.Deposit storage _d) external {
require(_d.inAwaitingSignerSetup(), "Not awaiting setup");
require(
block.timestamp > _d.signingGroupRequestedAt.add(TBTCConstants.getSigningGroupFormationTimeout()),
"Signing group formation timeout not yet elapsed"
);
// refund the deposit owner the cost to create a new Deposit at the time the Deposit was opened.
uint256 _seized = _d.seizeSignerBonds();
if(_seized >= _d.keepSetupFee){
/* solium-disable-next-line security/no-send */
_d.enableWithdrawal(_d.depositOwner(), _d.keepSetupFee);
_d.pushFundsToKeepGroup(_seized.sub(_d.keepSetupFee));
}
_d.setFailedSetup();
_d.logSetupFailed();
fundingTeardown(_d);
}
/// @notice we poll the Keep contract to retrieve our pubkey.
/// @dev We store the pubkey as 2 bytestrings, X and Y.
/// @param _d Deposit storage pointer.
/// @return True if successful, otherwise revert.
function retrieveSignerPubkey(DepositUtils.Deposit storage _d) public {
require(_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup");
bytes memory _publicKey = IBondedECDSAKeep(_d.keepAddress).getPublicKey();
require(_publicKey.length == 64, "public key not set or not 64-bytes long");
_d.signingGroupPubkeyX = _publicKey.slice(0, 32).toBytes32();
_d.signingGroupPubkeyY = _publicKey.slice(32, 32).toBytes32();
require(_d.signingGroupPubkeyY != bytes32(0) && _d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey");
_d.fundingProofTimerStart = block.timestamp;
_d.setAwaitingBTCFundingProof();
_d.logRegisteredPubkey(
_d.signingGroupPubkeyX,
_d.signingGroupPubkeyY);
}
/// @notice Anyone may notify the contract that the funder has failed to
/// prove that they have sent BTC in time.
/// @dev This is considered a funder fault, and the funder's payment for
/// opening the deposit is not refunded. Reverts if the funding timeout
/// has not yet elapsed, or if the deposit is not currently awaiting
/// funding proof.
/// @param _d Deposit storage pointer.
function notifyFundingTimedOut(DepositUtils.Deposit storage _d) external {
require(_d.inAwaitingBTCFundingProof(), "Funding timeout has not started");
require(
block.timestamp > _d.fundingProofTimerStart.add(TBTCConstants.getFundingTimeout()),
"Funding timeout has not elapsed."
);
_d.setFailedSetup();
_d.logSetupFailed();
_d.closeKeep();
fundingTeardown(_d);
}
/// @notice Requests a funder abort for a failed-funding deposit; that is,
/// requests return of a sent UTXO to `_abortOutputScript`. This can
/// be used for example when a UTXO is sent that is the wrong size
/// for the lot. Must be called after setup fails for any reason,
/// and imposes no requirement or incentive on the signing group to
/// return the UTXO.
/// @dev This is a self-admitted funder fault, and should only be callable
/// by the TDT holder.
/// @param _d Deposit storage pointer.
/// @param _abortOutputScript The output script the funder wishes to request
/// a return of their UTXO to.
function requestFunderAbort(
DepositUtils.Deposit storage _d,
bytes memory _abortOutputScript
) public { // not external to allow bytes memory parameters
require(
_d.inFailedSetup(),
"The deposit has not failed funding"
);
_d.logFunderRequestedAbort(_abortOutputScript);
}
/// @notice Anyone can provide a signature that was not requested to prove fraud during funding.
/// @dev Calls out to the keep to verify if there was fraud.
/// @param _d Deposit storage pointer.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value.
/// @param _signedDigest The digest signed by the signature vrs tuple.
/// @param _preimage The sha256 preimage of the digest.
/// @return True if successful, otherwise revert.
function provideFundingECDSAFraudProof(
DepositUtils.Deposit storage _d,
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public { // not external to allow bytes memory parameters
require(
_d.inAwaitingBTCFundingProof(),
"Signer fraud during funding flow only available while awaiting funding"
);
_d.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage);
_d.logFraudDuringSetup();
// Allow deposit owner to withdraw seized bonds after contract termination.
uint256 _seized = _d.seizeSignerBonds();
_d.enableWithdrawal(_d.depositOwner(), _seized);
fundingFraudTeardown(_d);
_d.setFailedSetup();
_d.logSetupFailed();
}
/// @notice Anyone may notify the deposit of a funding proof to activate the deposit.
/// This is the happy-path of the funding flow. It means that we have succeeded.
/// @dev Takes a pre-parsed transaction and calculates values needed to verify funding.
/// @param _d Deposit storage pointer.
/// @param _txVersion Transaction version number (4-byte LE).
/// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed).
/// @param _merkleProof The merkle proof of transaction inclusion in a block.
/// @param _txIndexInBlock Transaction index in the block (0-indexed).
/// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first.
function provideBTCFundingProof(
DepositUtils.Deposit storage _d,
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public { // not external to allow bytes memory parameters
require(_d.inAwaitingBTCFundingProof(), "Not awaiting funding");
bytes8 _valueBytes;
bytes memory _utxoOutpoint;
(_valueBytes, _utxoOutpoint) = _d.validateAndParseFundingSPVProof(
_txVersion,
_txInputVector,
_txOutputVector,
_txLocktime,
_fundingOutputIndex,
_merkleProof,
_txIndexInBlock,
_bitcoinHeaders
);
// Write down the UTXO info and set to active. Congratulations :)
_d.utxoValueBytes = _valueBytes;
_d.utxoOutpoint = _utxoOutpoint;
_d.fundedAt = block.timestamp;
bytes32 _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256();
fundingTeardown(_d);
_d.setActive();
_d.logFunded(_txid);
}
}
pragma solidity 0.5.17;
import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol";
import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol";
import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol";
import {CheckBitcoinSigs} from "@summa-tx/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol";
import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";
import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol";
import {DepositUtils} from "./DepositUtils.sol";
import {DepositStates} from "./DepositStates.sol";
import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol";
import {TBTCConstants} from "../system/TBTCConstants.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {DepositLiquidation} from "./DepositLiquidation.sol";
library DepositRedemption {
using SafeMath for uint256;
using CheckBitcoinSigs for bytes;
using BytesLib for bytes;
using BTCUtils for bytes;
using ValidateSPV for bytes;
using ValidateSPV for bytes32;
using DepositUtils for DepositUtils.Deposit;
using DepositStates for DepositUtils.Deposit;
using DepositLiquidation for DepositUtils.Deposit;
using OutsourceDepositLogging for DepositUtils.Deposit;
/// @notice Pushes signer fee to the Keep group by transferring it to the Keep address.
/// @dev Approves the keep contract, then expects it to call transferFrom.
function distributeSignerFee(DepositUtils.Deposit storage _d) internal {
IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress);
_d.tbtcToken.approve(_d.keepAddress, _d.signerFeeTbtc());
_keep.distributeERC20Reward(address(_d.tbtcToken), _d.signerFeeTbtc());
}
/// @notice Approves digest for signing by a keep.
/// @dev Calls given keep to sign the digest. Records a current timestamp
/// for given digest.
/// @param _digest Digest to approve.
function approveDigest(DepositUtils.Deposit storage _d, bytes32 _digest) internal {
IBondedECDSAKeep(_d.keepAddress).sign(_digest);
_d.approvedDigests[_digest] = block.timestamp;
}
/// @notice Handles TBTC requirements for redemption.
/// @dev Burns or transfers depending on term and supply-peg impact.
/// Once these transfers complete, the deposit balance should be
/// sufficient to pay out signer fees once the redemption transaction
/// is proven on the Bitcoin side.
function performRedemptionTbtcTransfers(DepositUtils.Deposit storage _d) internal {
address tdtHolder = _d.depositOwner();
address frtHolder = _d.feeRebateTokenHolder();
address vendingMachineAddress = _d.vendingMachineAddress;
(
uint256 tbtcOwedToDeposit,
uint256 tbtcOwedToTdtHolder,
uint256 tbtcOwedToFrtHolder
) = _d.calculateRedemptionTbtcAmounts(_d.redeemerAddress, false);
if(tbtcOwedToDeposit > 0){
_d.tbtcToken.transferFrom(msg.sender, address(this), tbtcOwedToDeposit);
}
if(tbtcOwedToTdtHolder > 0){
if(tdtHolder == vendingMachineAddress){
_d.tbtcToken.burn(tbtcOwedToTdtHolder);
} else {
_d.tbtcToken.transfer(tdtHolder, tbtcOwedToTdtHolder);
}
}
if(tbtcOwedToFrtHolder > 0){
_d.tbtcToken.transfer(frtHolder, tbtcOwedToFrtHolder);
}
}
function _requestRedemption(
DepositUtils.Deposit storage _d,
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript,
address payable _redeemer
) internal {
require(_d.inRedeemableState(), "Redemption only available from Active or Courtesy state");
bytes memory _output = abi.encodePacked(_outputValueBytes, _redeemerOutputScript);
require(_output.extractHash().length > 0, "Output script must be a standard type");
// set redeemerAddress early to enable direct access by other functions
_d.redeemerAddress = _redeemer;
performRedemptionTbtcTransfers(_d);
// Convert the 8-byte LE ints to uint256
uint256 _outputValue = abi.encodePacked(_outputValueBytes).reverseEndianness().bytesToUint();
uint256 _requestedFee = _d.utxoValue().sub(_outputValue);
require(_requestedFee >= TBTCConstants.getMinimumRedemptionFee(), "Fee is too low");
require(
_requestedFee < _d.utxoValue() / 2,
"Initial fee cannot exceed half of the deposit's value"
);
// Calculate the sighash
bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash(
_d.utxoOutpoint,
_d.signerPKH(),
_d.utxoValueBytes,
_outputValueBytes,
_redeemerOutputScript);
// write all request details
_d.redeemerOutputScript = _redeemerOutputScript;
_d.initialRedemptionFee = _requestedFee;
_d.latestRedemptionFee = _requestedFee;
_d.withdrawalRequestTime = block.timestamp;
_d.lastRequestedDigest = _sighash;
approveDigest(_d, _sighash);
_d.setAwaitingWithdrawalSignature();
_d.logRedemptionRequested(
_redeemer,
_sighash,
_d.utxoValue(),
_redeemerOutputScript,
_requestedFee,
_d.utxoOutpoint);
}
/// @notice Anyone can request redemption as long as they can.
/// approve the TDT transfer to the final recipient.
/// @dev The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption
/// on behalf of _finalRecipient.
/// @param _d Deposit storage pointer.
/// @param _outputValueBytes The 8-byte LE output size.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
/// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer.
function transferAndRequestRedemption(
DepositUtils.Deposit storage _d,
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript,
address payable _finalRecipient
) public { // not external to allow bytes memory parameters
_d.tbtcDepositToken.transferFrom(msg.sender, _finalRecipient, uint256(address(this)));
_requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, _finalRecipient);
}
/// @notice Only TDT holder can request redemption,
/// unless Deposit is expired or in COURTESY_CALL.
/// @dev The redeemer specifies details about the Bitcoin redemption transaction.
/// @param _d Deposit storage pointer.
/// @param _outputValueBytes The 8-byte LE output size.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
function requestRedemption(
DepositUtils.Deposit storage _d,
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript
) public { // not external to allow bytes memory parameters
_requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, msg.sender);
}
/// @notice Anyone may provide a withdrawal signature if it was requested.
/// @dev The signers will be penalized if this (or provideRedemptionProof) is not called.
/// @param _d Deposit storage pointer.
/// @param _v Signature recovery value.
/// @param _r Signature R value.
/// @param _s Signature S value. Should be in the low half of secp256k1 curve's order.
function provideRedemptionSignature(
DepositUtils.Deposit storage _d,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature");
// If we're outside of the signature window, we COULD punish signers here
// Instead, we consider this a no-harm-no-foul situation.
// The signers have not stolen funds. Most likely they've just inconvenienced someone
// Validate `s` value for a malleability concern described in EIP-2.
// Only signatures with `s` value in the lower half of the secp256k1
// curve's order are considered valid.
require(
uint256(_s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"Malleable signature - s should be in the low half of secp256k1 curve's order"
);
// The signature must be valid on the pubkey
require(
_d.signerPubkey().checkSig(
_d.lastRequestedDigest,
_v, _r, _s
),
"Invalid signature"
);
// A signature has been provided, now we wait for fee bump or redemption
_d.setAwaitingWithdrawalProof();
_d.logGotRedemptionSignature(
_d.lastRequestedDigest,
_r,
_s);
}
/// @notice Anyone may notify the contract that a fee bump is needed.
/// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE.
/// @param _d Deposit storage pointer.
/// @param _previousOutputValueBytes The previous output's value.
/// @param _newOutputValueBytes The new output's value.
function increaseRedemptionFee(
DepositUtils.Deposit storage _d,
bytes8 _previousOutputValueBytes,
bytes8 _newOutputValueBytes
) public {
require(_d.inAwaitingWithdrawalProof(), "Fee increase only available after signature provided");
require(block.timestamp >= _d.withdrawalRequestTime.add(TBTCConstants.getIncreaseFeeTimer()), "Fee increase not yet permitted");
uint256 _newOutputValue = checkRelationshipToPrevious(_d, _previousOutputValueBytes, _newOutputValueBytes);
// If the fee bump shrinks the UTXO value below the minimum allowed
// value, clamp it to that minimum. Further fee bumps will be disallowed
// by checkRelationshipToPrevious.
if (_newOutputValue < TBTCConstants.getMinimumUtxoValue()) {
_newOutputValue = TBTCConstants.getMinimumUtxoValue();
}
_d.latestRedemptionFee = _d.utxoValue().sub(_newOutputValue);
// Calculate the next sighash
bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash(
_d.utxoOutpoint,
_d.signerPKH(),
_d.utxoValueBytes,
_newOutputValueBytes,
_d.redeemerOutputScript);
// Ratchet the signature and redemption proof timeouts
_d.withdrawalRequestTime = block.timestamp;
_d.lastRequestedDigest = _sighash;
approveDigest(_d, _sighash);
// Go back to waiting for a signature
_d.setAwaitingWithdrawalSignature();
_d.logRedemptionRequested(
msg.sender,
_sighash,
_d.utxoValue(),
_d.redeemerOutputScript,
_d.latestRedemptionFee,
_d.utxoOutpoint);
}
function checkRelationshipToPrevious(
DepositUtils.Deposit storage _d,
bytes8 _previousOutputValueBytes,
bytes8 _newOutputValueBytes
) public view returns (uint256 _newOutputValue){
// Check that we're incrementing the fee by exactly the redeemer's initial fee
uint256 _previousOutputValue = DepositUtils.bytes8LEToUint(_previousOutputValueBytes);
_newOutputValue = DepositUtils.bytes8LEToUint(_newOutputValueBytes);
require(_previousOutputValue.sub(_newOutputValue) == _d.initialRedemptionFee, "Not an allowed fee step");
// Calculate the previous one so we can check that it really is the previous one
bytes32 _previousSighash = CheckBitcoinSigs.wpkhSpendSighash(
_d.utxoOutpoint,
_d.signerPKH(),
_d.utxoValueBytes,
_previousOutputValueBytes,
_d.redeemerOutputScript);
require(
_d.wasDigestApprovedForSigning(_previousSighash) == _d.withdrawalRequestTime,
"Provided previous value does not yield previous sighash"
);
}
/// @notice Anyone may provide a withdrawal proof to prove redemption.
/// @dev The signers will be penalized if this is not called.
/// @param _d Deposit storage pointer.
/// @param _txVersion Transaction version number (4-byte LE).
/// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @param _txLocktime Final 4 bytes of the transaction.
/// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block.
/// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed).
/// @param _bitcoinHeaders An array of tightly-packed bitcoin headers.
function provideRedemptionProof(
DepositUtils.Deposit storage _d,
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
bytes memory _bitcoinHeaders
) public { // not external to allow bytes memory parameters
bytes32 _txid;
uint256 _fundingOutputValue;
require(_d.inRedemption(), "Redemption proof only allowed from redemption flow");
_fundingOutputValue = redemptionTransactionChecks(_d, _txInputVector, _txOutputVector);
_txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256();
_d.checkProofFromTxId(_txid, _merkleProof, _txIndexInBlock, _bitcoinHeaders);
require((_d.utxoValue().sub(_fundingOutputValue)) <= _d.latestRedemptionFee, "Incorrect fee amount");
// Transfer TBTC to signers and close the keep.
distributeSignerFee(_d);
_d.closeKeep();
_d.distributeFeeRebate();
// We're done yey!
_d.setRedeemed();
_d.redemptionTeardown();
_d.logRedeemed(_txid);
}
/// @notice Check the redemption transaction input and output vector to ensure the transaction spends
/// the correct UTXO and sends value to the appropriate public key hash.
/// @dev We only look at the first input and first output. Revert if we find the wrong UTXO or value recipient.
/// It's safe to look at only the first input/output as anything that breaks this can be considered fraud
/// and can be caught by ECDSAFraudProof.
/// @param _d Deposit storage pointer.
/// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs.
/// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs.
/// @return The value sent to the redeemer's public key hash.
function redemptionTransactionChecks(
DepositUtils.Deposit storage _d,
bytes memory _txInputVector,
bytes memory _txOutputVector
) public view returns (uint256) {
require(_txInputVector.validateVin(), "invalid input vector provided");
require(_txOutputVector.validateVout(), "invalid output vector provided");
bytes memory _input = _txInputVector.slice(1, _txInputVector.length-1);
require(
keccak256(_input.extractOutpoint()) == keccak256(_d.utxoOutpoint),
"Tx spends the wrong UTXO"
);
bytes memory _output = _txOutputVector.slice(1, _txOutputVector.length-1);
bytes memory _expectedOutputScript = _d.redeemerOutputScript;
require(_output.length - 8 >= _d.redeemerOutputScript.length, "Output script is too short to extract the expected script");
require(
keccak256(_output.slice(8, _expectedOutputScript.length)) == keccak256(_expectedOutputScript),
"Tx sends value to wrong output script"
);
return (uint256(_output.extractValue()));
}
/// @notice Anyone may notify the contract that the signers have failed to produce a signature.
/// @dev This is considered fraud, and is punished.
/// @param _d Deposit storage pointer.
function notifyRedemptionSignatureTimedOut(DepositUtils.Deposit storage _d) external {
require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature");
require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getSignatureTimeout()), "Signature timer has not elapsed");
_d.startLiquidation(false); // not fraud, just failure
}
/// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof.
/// @dev This is considered fraud, and is punished.
/// @param _d Deposit storage pointer.
function notifyRedemptionProofTimedOut(DepositUtils.Deposit storage _d) external {
require(_d.inAwaitingWithdrawalProof(), "Not currently awaiting a redemption proof");
require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getRedemptionProofTimeout()), "Proof timer has not elapsed");
_d.startLiquidation(false); // not fraud, just failure
}
}
pragma solidity 0.5.17;
library TBTCConstants {
// This is intended to make it easy to update system params
// During testing swap this out with another constats contract
// System Parameters
uint256 public constant BENEFICIARY_FEE_DIVISOR = 1000; // 1/1000 = 10 bps = 0.1% = 0.001
uint256 public constant SATOSHI_MULTIPLIER = 10 ** 10; // multiplier to convert satoshi to TBTC token units
uint256 public constant DEPOSIT_TERM_LENGTH = 180 * 24 * 60 * 60; // 180 days in seconds
uint256 public constant TX_PROOF_DIFFICULTY_FACTOR = 6; // confirmations on the Bitcoin chain
// Redemption Flow
uint256 public constant REDEMPTION_SIGNATURE_TIMEOUT = 2 * 60 * 60; // seconds
uint256 public constant INCREASE_FEE_TIMER = 4 * 60 * 60; // seconds
uint256 public constant REDEMPTION_PROOF_TIMEOUT = 6 * 60 * 60; // seconds
uint256 public constant MINIMUM_REDEMPTION_FEE = 2000; // satoshi
uint256 public constant MINIMUM_UTXO_VALUE = 2000; // satoshi
// Funding Flow
uint256 public constant FUNDING_PROOF_TIMEOUT = 3 * 60 * 60; // seconds
uint256 public constant FORMATION_TIMEOUT = 3 * 60 * 60; // seconds
// Liquidation Flow
uint256 public constant COURTESY_CALL_DURATION = 6 * 60 * 60; // seconds
uint256 public constant AUCTION_DURATION = 24 * 60 * 60; // seconds
// Getters for easy access
function getBeneficiaryRewardDivisor() external pure returns (uint256) { return BENEFICIARY_FEE_DIVISOR; }
function getSatoshiMultiplier() external pure returns (uint256) { return SATOSHI_MULTIPLIER; }
function getDepositTerm() external pure returns (uint256) { return DEPOSIT_TERM_LENGTH; }
function getTxProofDifficultyFactor() external pure returns (uint256) { return TX_PROOF_DIFFICULTY_FACTOR; }
function getSignatureTimeout() external pure returns (uint256) { return REDEMPTION_SIGNATURE_TIMEOUT; }
function getIncreaseFeeTimer() external pure returns (uint256) { return INCREASE_FEE_TIMER; }
function getRedemptionProofTimeout() external pure returns (uint256) { return REDEMPTION_PROOF_TIMEOUT; }
function getMinimumRedemptionFee() external pure returns (uint256) { return MINIMUM_REDEMPTION_FEE; }
function getMinimumUtxoValue() external pure returns (uint256) { return MINIMUM_UTXO_VALUE; }
function getFundingTimeout() external pure returns (uint256) { return FUNDING_PROOF_TIMEOUT; }
function getSigningGroupFormationTimeout() external pure returns (uint256) { return FORMATION_TIMEOUT; }
function getCourtesyCallTimeout() external pure returns (uint256) { return COURTESY_CALL_DURATION; }
function getAuctionDuration() external pure returns (uint256) { return AUCTION_DURATION; }
}
pragma solidity 0.5.17;
import {DepositLog} from "../DepositLog.sol";
import {DepositUtils} from "./DepositUtils.sol";
library OutsourceDepositLogging {
/// @notice Fires a Created event.
/// @dev `DepositLog.logCreated` fires a Created event with
/// _keepAddress, msg.sender and block.timestamp.
/// msg.sender will be the calling Deposit's address.
/// @param _keepAddress The address of the associated keep.
function logCreated(DepositUtils.Deposit storage _d, address _keepAddress) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logCreated(_keepAddress);
}
/// @notice Fires a RedemptionRequested event.
/// @dev This is the only event without an explicit timestamp.
/// @param _redeemer The ethereum address of the redeemer.
/// @param _digest The calculated sighash digest.
/// @param _utxoValue The size of the utxo in sat.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
/// @param _requestedFee The redeemer or bump-system specified fee.
/// @param _outpoint The 36 byte outpoint.
/// @return True if successful, else revert.
function logRedemptionRequested(
DepositUtils.Deposit storage _d,
address _redeemer,
bytes32 _digest,
uint256 _utxoValue,
bytes memory _redeemerOutputScript,
uint256 _requestedFee,
bytes memory _outpoint
) public { // not external to allow bytes memory parameters
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logRedemptionRequested(
_redeemer,
_digest,
_utxoValue,
_redeemerOutputScript,
_requestedFee,
_outpoint
);
}
/// @notice Fires a GotRedemptionSignature event.
/// @dev We append the sender, which is the deposit contract that called.
/// @param _digest Signed digest.
/// @param _r Signature r value.
/// @param _s Signature s value.
/// @return True if successful, else revert.
function logGotRedemptionSignature(
DepositUtils.Deposit storage _d,
bytes32 _digest,
bytes32 _r,
bytes32 _s
) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logGotRedemptionSignature(
_digest,
_r,
_s
);
}
/// @notice Fires a RegisteredPubkey event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logRegisteredPubkey(
DepositUtils.Deposit storage _d,
bytes32 _signingGroupPubkeyX,
bytes32 _signingGroupPubkeyY
) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logRegisteredPubkey(
_signingGroupPubkeyX,
_signingGroupPubkeyY);
}
/// @notice Fires a SetupFailed event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logSetupFailed(DepositUtils.Deposit storage _d) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logSetupFailed();
}
/// @notice Fires a FunderAbortRequested event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logFunderRequestedAbort(
DepositUtils.Deposit storage _d,
bytes memory _abortOutputScript
) public { // not external to allow bytes memory parameters
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logFunderRequestedAbort(_abortOutputScript);
}
/// @notice Fires a FraudDuringSetup event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logFraudDuringSetup(DepositUtils.Deposit storage _d) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logFraudDuringSetup();
}
/// @notice Fires a Funded event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logFunded(DepositUtils.Deposit storage _d, bytes32 _txid) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logFunded(_txid);
}
/// @notice Fires a CourtesyCalled event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logCourtesyCalled(DepositUtils.Deposit storage _d) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logCourtesyCalled();
}
/// @notice Fires a StartedLiquidation event.
/// @dev We append the sender, which is the deposit contract that called.
/// @param _wasFraud True if liquidating for fraud.
function logStartedLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logStartedLiquidation(_wasFraud);
}
/// @notice Fires a Redeemed event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logRedeemed(DepositUtils.Deposit storage _d, bytes32 _txid) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logRedeemed(_txid);
}
/// @notice Fires a Liquidated event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logLiquidated(DepositUtils.Deposit storage _d) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logLiquidated();
}
/// @notice Fires a ExitedCourtesyCall event.
/// @dev The logger is on a system contract, so all logs from all deposits are from the same address.
function logExitedCourtesyCall(DepositUtils.Deposit storage _d) external {
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logExitedCourtesyCall();
}
}
pragma solidity 0.5.17;
import {TBTCDepositToken} from "./system/TBTCDepositToken.sol";
// solium-disable function-order
// Below, a few functions must be public to allow bytes memory parameters, but
// their being so triggers errors because public functions should be grouped
// below external functions. Since these would be external if it were possible,
// we ignore the issue.
contract DepositLog {
/*
Logging philosophy:
Every state transition should fire a log
That log should have ALL necessary info for off-chain actors
Everyone should be able to ENTIRELY rely on log messages
*/
// `TBTCDepositToken` mints a token for every new Deposit.
// If a token exists for a given ID, we know it is a valid Deposit address.
TBTCDepositToken tbtcDepositToken;
// This event is fired when we init the deposit
event Created(
address indexed _depositContractAddress,
address indexed _keepAddress,
uint256 _timestamp
);
// This log event contains all info needed to rebuild the redemption tx
// We index on request and signers and digest
event RedemptionRequested(
address indexed _depositContractAddress,
address indexed _requester,
bytes32 indexed _digest,
uint256 _utxoValue,
bytes _redeemerOutputScript,
uint256 _requestedFee,
bytes _outpoint
);
// This log event contains all info needed to build a witnes
// We index the digest so that we can search events for the other log
event GotRedemptionSignature(
address indexed _depositContractAddress,
bytes32 indexed _digest,
bytes32 _r,
bytes32 _s,
uint256 _timestamp
);
// This log is fired when the signing group returns a public key
event RegisteredPubkey(
address indexed _depositContractAddress,
bytes32 _signingGroupPubkeyX,
bytes32 _signingGroupPubkeyY,
uint256 _timestamp
);
// This event is fired when we enter the FAILED_SETUP state for any reason
event SetupFailed(
address indexed _depositContractAddress,
uint256 _timestamp
);
// This event is fired when a funder requests funder abort after
// FAILED_SETUP has been reached. Funder abort is a voluntary signer action
// to return UTXO(s) that were sent to a signer-controlled wallet despite
// the funding proofs having failed.
event FunderAbortRequested(
address indexed _depositContractAddress,
bytes _abortOutputScript
);
// This event is fired when we detect an ECDSA fraud before seeing a funding proof
event FraudDuringSetup(
address indexed _depositContractAddress,
uint256 _timestamp
);
// This event is fired when we enter the ACTIVE state
event Funded(
address indexed _depositContractAddress,
bytes32 indexed _txid,
uint256 _timestamp
);
// This event is called when we enter the COURTESY_CALL state
event CourtesyCalled(
address indexed _depositContractAddress,
uint256 _timestamp
);
// This event is fired when we go from COURTESY_CALL to ACTIVE
event ExitedCourtesyCall(
address indexed _depositContractAddress,
uint256 _timestamp
);
// This log event is fired when liquidation
event StartedLiquidation(
address indexed _depositContractAddress,
bool _wasFraud,
uint256 _timestamp
);
// This event is fired when the Redemption SPV proof is validated
event Redeemed(
address indexed _depositContractAddress,
bytes32 indexed _txid,
uint256 _timestamp
);
// This event is fired when Liquidation is completed
event Liquidated(
address indexed _depositContractAddress,
uint256 _timestamp
);
//
// Logging
//
/// @notice Fires a Created event.
/// @dev We append the sender, which is the deposit contract that called.
/// @param _keepAddress The address of the associated keep.
/// @return True if successful, else revert.
function logCreated(address _keepAddress) external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit Created(msg.sender, _keepAddress, block.timestamp);
}
/// @notice Fires a RedemptionRequested event.
/// @dev This is the only event without an explicit timestamp.
/// @param _requester The ethereum address of the requester.
/// @param _digest The calculated sighash digest.
/// @param _utxoValue The size of the utxo in sat.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
/// @param _requestedFee The requester or bump-system specified fee.
/// @param _outpoint The 36 byte outpoint.
/// @return True if successful, else revert.
function logRedemptionRequested(
address _requester,
bytes32 _digest,
uint256 _utxoValue,
bytes memory _redeemerOutputScript,
uint256 _requestedFee,
bytes memory _outpoint
) public {
// not external to allow bytes memory parameters
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit RedemptionRequested(
msg.sender,
_requester,
_digest,
_utxoValue,
_redeemerOutputScript,
_requestedFee,
_outpoint
);
}
/// @notice Fires a GotRedemptionSignature event.
/// @dev We append the sender, which is the deposit contract that called.
/// @param _digest signed digest.
/// @param _r signature r value.
/// @param _s signature s value.
function logGotRedemptionSignature(bytes32 _digest, bytes32 _r, bytes32 _s)
external
{
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit GotRedemptionSignature(
msg.sender,
_digest,
_r,
_s,
block.timestamp
);
}
/// @notice Fires a RegisteredPubkey event.
/// @dev We append the sender, which is the deposit contract that called.
function logRegisteredPubkey(
bytes32 _signingGroupPubkeyX,
bytes32 _signingGroupPubkeyY
) external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit RegisteredPubkey(
msg.sender,
_signingGroupPubkeyX,
_signingGroupPubkeyY,
block.timestamp
);
}
/// @notice Fires a SetupFailed event.
/// @dev We append the sender, which is the deposit contract that called.
function logSetupFailed() external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit SetupFailed(msg.sender, block.timestamp);
}
/// @notice Fires a FunderAbortRequested event.
/// @dev We append the sender, which is the deposit contract that called.
function logFunderRequestedAbort(bytes memory _abortOutputScript) public {
// not external to allow bytes memory parameters
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit FunderAbortRequested(msg.sender, _abortOutputScript);
}
/// @notice Fires a FraudDuringSetup event.
/// @dev We append the sender, which is the deposit contract that called.
function logFraudDuringSetup() external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit FraudDuringSetup(msg.sender, block.timestamp);
}
/// @notice Fires a Funded event.
/// @dev We append the sender, which is the deposit contract that called.
function logFunded(bytes32 _txid) external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit Funded(msg.sender, _txid, block.timestamp);
}
/// @notice Fires a CourtesyCalled event.
/// @dev We append the sender, which is the deposit contract that called.
function logCourtesyCalled() external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit CourtesyCalled(msg.sender, block.timestamp);
}
/// @notice Fires a StartedLiquidation event.
/// @dev We append the sender, which is the deposit contract that called.
/// @param _wasFraud True if liquidating for fraud.
function logStartedLiquidation(bool _wasFraud) external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit StartedLiquidation(msg.sender, _wasFraud, block.timestamp);
}
/// @notice Fires a Redeemed event
/// @dev We append the sender, which is the deposit contract that called.
function logRedeemed(bytes32 _txid) external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit Redeemed(msg.sender, _txid, block.timestamp);
}
/// @notice Fires a Liquidated event
/// @dev We append the sender, which is the deposit contract that called.
function logLiquidated() external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit Liquidated(msg.sender, block.timestamp);
}
/// @notice Fires a ExitedCourtesyCall event
/// @dev We append the sender, which is the deposit contract that called.
function logExitedCourtesyCall() external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit ExitedCourtesyCall(msg.sender, block.timestamp);
}
/// @notice Sets the tbtcDepositToken contract.
/// @dev The contract is used by `approvedToLog` to check if the
/// caller is a Deposit contract. This should only be called once.
/// @param _tbtcDepositTokenAddress The address of the tbtcDepositToken.
function setTbtcDepositToken(TBTCDepositToken _tbtcDepositTokenAddress)
internal
{
require(
address(tbtcDepositToken) == address(0),
"tbtcDepositToken is already set"
);
tbtcDepositToken = _tbtcDepositTokenAddress;
}
//
// AUTH
//
/// @notice Checks if an address is an allowed logger.
/// @dev checks tbtcDepositToken to see if the caller represents
/// an existing deposit.
/// We don't require this, so deposits are not bricked if the system borks.
/// @param _caller The address of the calling contract.
/// @return True if approved, otherwise false.
function approvedToLog(address _caller) public view returns (bool) {
return tbtcDepositToken.exists(uint256(_caller));
}
}
pragma solidity 0.5.17;
import {ERC721Metadata} from "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol";
import {DepositFactoryAuthority} from "./DepositFactoryAuthority.sol";
import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol";
/// @title tBTC Deposit Token for tracking deposit ownership
/// @notice The tBTC Deposit Token, commonly referenced as the TDT, is an
/// ERC721 non-fungible token whose ownership reflects the ownership
/// of its corresponding deposit. Each deposit has one TDT, and vice
/// versa. Owning a TDT is equivalent to owning its corresponding
/// deposit. TDTs can be transferred freely. tBTC's VendingMachine
/// contract takes ownership of TDTs and in exchange returns fungible
/// TBTC tokens whose value is backed 1-to-1 by the corresponding
/// deposit's BTC.
/// @dev Currently, TDTs are minted using the uint256 casting of the
/// corresponding deposit contract's address. That is, the TDT's id is
/// convertible to the deposit's address and vice versa. TDTs are minted
/// automatically by the factory during each deposit's initialization. See
/// DepositFactory.createNewDeposit() for more info on how the TDT is minted.
contract TBTCDepositToken is ERC721Metadata, DepositFactoryAuthority {
constructor(address _depositFactoryAddress)
ERC721Metadata("tBTC Deposit Token", "TDT")
public {
initialize(_depositFactoryAddress);
}
/// @dev Mints a new token.
/// Reverts if the given token ID already exists.
/// @param _to The address that will own the minted token
/// @param _tokenId uint256 ID of the token to be minted
function mint(address _to, uint256 _tokenId) external onlyFactory {
_mint(_to, _tokenId);
}
/// @dev Returns whether the specified token exists.
/// @param _tokenId uint256 ID of the token to query the existence of.
/// @return bool whether the token exists.
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
/// @notice Allow another address to spend on the caller's behalf.
/// Set allowance for other address and notify.
/// Allows `_spender` to transfer the specified TDT
/// on your behalf and then ping the contract about it.
/// @dev The `_spender` should implement the `ITokenRecipient`
/// interface below to receive approval notifications.
/// @param _spender `ITokenRecipient`-conforming contract authorized to
/// operate on the approved token.
/// @param _tdtId The TDT they can spend.
/// @param _extraData Extra information to send to the approved contract.
function approveAndCall(
ITokenRecipient _spender,
uint256 _tdtId,
bytes memory _extraData
) public returns (bool) { // not external to allow bytes memory parameters
approve(address(_spender), _tdtId);
_spender.receiveApproval(msg.sender, _tdtId, address(this), _extraData);
return true;
}
}
/*
Authored by Satoshi Nakamoto 🤪
*/
pragma solidity 0.5.17;
import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import {ERC20Detailed} from "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
import {VendingMachineAuthority} from "./VendingMachineAuthority.sol";
import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol";
/// @title TBTC Token.
/// @notice This is the TBTC ERC20 contract.
/// @dev Tokens can only be minted by the `VendingMachine` contract.
contract TBTCToken is ERC20Detailed, ERC20, VendingMachineAuthority {
/// @dev Constructor, calls ERC20Detailed constructor to set Token info
/// ERC20Detailed(TokenName, TokenSymbol, NumberOfDecimals)
constructor(address _VendingMachine)
ERC20Detailed("tBTC", "TBTC", 18)
VendingMachineAuthority(_VendingMachine)
public {
// solium-disable-previous-line no-empty-blocks
}
/// @dev Mints an amount of the token and assigns it to an account.
/// Uses the internal _mint function.
/// @param _account The account that will receive the created tokens.
/// @param _amount The amount of tokens that will be created.
function mint(address _account, uint256 _amount) public onlyVendingMachine returns (bool) {
// NOTE: this is a public function with unchecked minting.
_mint(_account, _amount);
return true;
}
/// @dev Burns an amount of the token from the given account's balance.
/// deducting from the sender's allowance for said account.
/// Uses the internal _burn function.
/// @param _account The account whose tokens will be burnt.
/// @param _amount The amount of tokens that will be burnt.
function burnFrom(address _account, uint256 _amount) public {
_burnFrom(_account, _amount);
}
/// @dev Destroys `amount` tokens from `msg.sender`, reducing the
/// total supply.
/// @param _amount The amount of tokens that will be burnt.
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
/// @notice Set allowance for other address and notify.
/// Allows `_spender` to spend no more than `_value`
/// tokens on your behalf and then ping the contract about
/// it.
/// @dev The `_spender` should implement the `ITokenRecipient`
/// interface to receive approval notifications.
/// @param _spender Address of contract authorized to spend.
/// @param _value The max amount they can spend.
/// @param _extraData Extra information to send to the approved contract.
/// @return true if the `_spender` was successfully approved and acted on
/// the approval, false (or revert) otherwise.
function approveAndCall(ITokenRecipient _spender, uint256 _value, bytes memory _extraData) public returns (bool) {
if (approve(address(_spender), _value)) {
_spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
return false;
}
}
pragma solidity 0.5.17;
/// @title Deposit Factory Authority
/// @notice Contract to secure function calls to the Deposit Factory.
/// @dev Secured by setting the depositFactory address and using the onlyFactory
/// modifier on functions requiring restriction.
contract DepositFactoryAuthority {
bool internal _initialized = false;
address internal _depositFactory;
/// @notice Set the address of the System contract on contract
/// initialization.
/// @dev Since this function is not access-controlled, it should be called
/// transactionally with contract instantiation. In cases where a
/// regular contract directly inherits from DepositFactoryAuthority,
/// that should happen in the constructor. In cases where the inheritor
/// is binstead used via a clone factory, the same function that
/// creates a new clone should also trigger initialization.
function initialize(address _factory) public {
require(_factory != address(0), "Factory cannot be the zero address.");
require(! _initialized, "Factory can only be initialized once.");
_depositFactory = _factory;
_initialized = true;
}
/// @notice Function modifier ensures modified function is only called by set deposit factory.
modifier onlyFactory(){
require(_initialized, "Factory initialization must have been called.");
require(msg.sender == _depositFactory, "Caller must be depositFactory contract");
_;
}
}
pragma solidity 0.5.17;
/// @title TBTC System Authority.
/// @notice Contract to secure function calls to the TBTC System contract.
/// @dev The `TBTCSystem` contract address is passed as a constructor parameter.
contract TBTCSystemAuthority {
address internal tbtcSystemAddress;
/// @notice Set the address of the System contract on contract initialization.
constructor(address _tbtcSystemAddress) public {
tbtcSystemAddress = _tbtcSystemAddress;
}
/// @notice Function modifier ensures modified function is only called by TBTCSystem.
modifier onlyTbtcSystem(){
require(msg.sender == tbtcSystemAddress, "Caller must be tbtcSystem contract");
_;
}
}
pragma solidity 0.5.17;
/// @title Vending Machine Authority.
/// @notice Contract to secure function calls to the Vending Machine.
/// @dev Secured by setting the VendingMachine address and using the
/// onlyVendingMachine modifier on functions requiring restriction.
contract VendingMachineAuthority {
address internal VendingMachine;
constructor(address _vendingMachine) public {
VendingMachine = _vendingMachine;
}
/// @notice Function modifier ensures modified function caller address is the vending machine.
modifier onlyVendingMachine() {
require(msg.sender == VendingMachine, "caller must be the vending machine");
_;
}
}
pragma solidity 0.5.17;
/// @title Interface of recipient contract for `approveAndCall` pattern.
/// Implementors will be able to be used in an `approveAndCall`
/// interaction with a supporting contract, such that a token approval
/// can call the contract acting on that approval in a single
/// transaction.
///
/// See the `FundingScript` and `RedemptionScript` contracts as examples.
interface ITokenRecipient {
/// Typically called from a token contract's `approveAndCall` method, this
/// method will receive the original owner of the token (`_from`), the
/// transferred `_value` (in the case of an ERC721, the token id), the token
/// address (`_token`), and a blob of `_extraData` that is informally
/// specified by the implementor of this method as a way to communicate
/// additional parameters.
///
/// Token calls to `receiveApproval` should revert if `receiveApproval`
/// reverts, and reverts should remove the approval.
///
/// @param _from The original owner of the token approved for transfer.
/// @param _value For an ERC20, the amount approved for transfer; for an
/// ERC721, the id of the token approved for transfer.
/// @param _token The address of the contract for the token whose transfer
/// was approved.
/// @param _extraData An additional data blob forwarded unmodified through
/// `approveAndCall`, used to allow the token owner to pass
/// additional parameters and data to this method. The structure of
/// the extra data is informally specified by the implementor of
/// this interface.
function receiveApproval(
address _from,
uint256 _value,
address _token,
bytes calldata _extraData
) external;
}
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol";
import "./VendingMachineAuthority.sol";
/// @title Fee Rebate Token
/// @notice The Fee Rebate Token (FRT) is a non fungible token (ERC721)
/// the ID of which corresponds to a given deposit address.
/// If the corresponding deposit is still active, ownership of this token
/// could result in reimbursement of the signer fee paid to open the deposit.
/// @dev This token is minted automatically when a TDT (`TBTCDepositToken`)
/// is exchanged for TBTC (`TBTCToken`) via the Vending Machine (`VendingMachine`).
/// When the Deposit is redeemed, the TDT holder will be reimbursed
/// the signer fee if the redeemer is not the TDT holder and Deposit is not
/// at-term or in COURTESY_CALL.
contract FeeRebateToken is ERC721Metadata, VendingMachineAuthority {
constructor(address _vendingMachine)
ERC721Metadata("tBTC Fee Rebate Token", "FRT")
VendingMachineAuthority(_vendingMachine)
public {
// solium-disable-previous-line no-empty-blocks
}
/// @dev Mints a new token.
/// Reverts if the given token ID already exists.
/// @param _to The address that will own the minted token.
/// @param _tokenId uint256 ID of the token to be minted.
function mint(address _to, uint256 _tokenId) external onlyVendingMachine {
_mint(_to, _tokenId);
}
/// @dev Returns whether the specified token exists.
/// @param _tokenId uint256 ID of the token to query the existence of.
/// @return bool whether the token exists.
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
}
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
/// @title ECDSA Keep
/// @notice Contract reflecting an ECDSA keep.
contract IBondedECDSAKeep {
/// @notice Returns public key of this keep.
/// @return Keeps's public key.
function getPublicKey() external view returns (bytes memory);
/// @notice Returns the amount of the keep's ETH bond in wei.
/// @return The amount of the keep's ETH bond in wei.
function checkBondAmount() external view returns (uint256);
/// @notice Calculates a signature over provided digest by the keep. Note that
/// signatures from the keep not explicitly requested by calling `sign`
/// will be provable as fraud via `submitSignatureFraud`.
/// @param _digest Digest to be signed.
function sign(bytes32 _digest) external;
/// @notice Distributes ETH reward evenly across keep signer beneficiaries.
/// @dev Only the value passed to this function is distributed.
function distributeETHReward() external payable;
/// @notice Distributes ERC20 reward evenly across keep signer beneficiaries.
/// @dev This works with any ERC20 token that implements a transferFrom
/// function.
/// This function only has authority over pre-approved
/// token amount. We don't explicitly check for allowance, SafeMath
/// subtraction overflow is enough protection.
/// @param _tokenAddress Address of the ERC20 token to distribute.
/// @param _value Amount of ERC20 token to distribute.
function distributeERC20Reward(address _tokenAddress, uint256 _value)
external;
/// @notice Seizes the signers' ETH bonds. After seizing bonds keep is
/// terminated so it will no longer respond to signing requests. Bonds can
/// be seized only when there is no signing in progress or requested signing
/// process has timed out. This function seizes all of signers' bonds.
/// The application may decide to return part of bonds later after they are
/// processed using returnPartialSignerBonds function.
function seizeSignerBonds() external;
/// @notice Returns partial signer's ETH bonds to the pool as an unbounded
/// value. This function is called after bonds have been seized and processed
/// by the privileged application after calling seizeSignerBonds function.
/// It is entirely up to the application if a part of signers' bonds is
/// returned. The application may decide for that but may also decide to
/// seize bonds and do not return anything.
function returnPartialSignerBonds() external payable;
/// @notice Submits a fraud proof for a valid signature from this keep that was
/// not first approved via a call to sign.
/// @dev The function expects the signed digest to be calculated as a sha256
/// hash of the preimage: `sha256(_preimage)`.
/// @param _v Signature's header byte: `27 + recoveryID`.
/// @param _r R part of ECDSA signature.
/// @param _s S part of ECDSA signature.
/// @param _signedDigest Digest for the provided signature. Result of hashing
/// the preimage.
/// @param _preimage Preimage of the hashed message.
/// @return True if fraud, error otherwise.
function submitSignatureFraud(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes calldata _preimage
)
external returns (bool _isFraud);
/// @notice Closes keep when no longer needed. Releases bonds to the keep
/// members. Keep can be closed only when there is no signing in progress or
/// requested signing process has timed out.
/// @dev The function can be called only by the owner of the keep and only
/// if the keep has not been already closed.
function closeKeep() external;
}
pragma solidity ^0.5.10;
/** @title ValidateSPV*/
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
import {BTCUtils} from "./BTCUtils.sol";
library ValidateSPV {
using BTCUtils for bytes;
using BTCUtils for uint256;
using BytesLib for bytes;
using SafeMath for uint256;
enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS }
enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD }
uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;
uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;
function getErrBadLength() internal pure returns (uint256) {
return ERR_BAD_LENGTH;
}
function getErrInvalidChain() internal pure returns (uint256) {
return ERR_INVALID_CHAIN;
}
function getErrLowWork() internal pure returns (uint256) {
return ERR_LOW_WORK;
}
/// @notice Validates a tx inclusion in the block
/// @dev `index` is not a reliable indicator of location within a block
/// @param _txid The txid (LE)
/// @param _merkleRoot The merkle root (as in the block header)
/// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)
/// @param _index The leaf's index in the tree (0-indexed)
/// @return true if fully valid, false otherwise
function prove(
bytes32 _txid,
bytes32 _merkleRoot,
bytes memory _intermediateNodes,
uint _index
) internal pure returns (bool) {
// Shortcut the empty-block case
if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) {
return true;
}
bytes memory _proof = abi.encodePacked(_txid, _intermediateNodes, _merkleRoot);
// If the Merkle proof failed, bubble up error
return _proof.verifyHash256Merkle(_index);
}
/// @notice Hashes transaction to get txid
/// @dev Supports Legacy and Witness
/// @param _version 4-bytes version
/// @param _vin Raw bytes length-prefixed input vector
/// @param _vout Raw bytes length-prefixed output vector
/// @param _locktime 4-byte tx locktime
/// @return 32-byte transaction id, little endian
function calculateTxId(
bytes memory _version,
bytes memory _vin,
bytes memory _vout,
bytes memory _locktime
) internal pure returns (bytes32) {
// Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)
return abi.encodePacked(_version, _vin, _vout, _locktime).hash256();
}
/// @notice Checks validity of header chain
/// @notice Compares the hash of each header to the prevHash in the next header
/// @param _headers Raw byte array of header chain
/// @return The total accumulated difficulty of the header chain, or an error code
function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) {
// Check header chain length
if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;}
// Initialize header start index
bytes32 _digest;
_totalDifficulty = 0;
for (uint256 _start = 0; _start < _headers.length; _start += 80) {
// ith header start index and ith header
bytes memory _header = _headers.slice(_start, 80);
// After the first header, check that headers are in a chain
if (_start != 0) {
if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;}
}
// ith header target
uint256 _target = _header.extractTarget();
// Require that the header has sufficient work
_digest = _header.hash256View();
if(uint256(_digest).reverseUint256() > _target) {
return ERR_LOW_WORK;
}
// Add ith header difficulty to difficulty sum
_totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty());
}
}
/// @notice Checks validity of header work
/// @param _digest Header digest
/// @param _target The target threshold
/// @return true if header work is valid, false otherwise
function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) {
if (_digest == bytes32(0)) {return false;}
return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target);
}
/// @notice Checks validity of header chain
/// @dev Compares current header prevHash to previous header's digest
/// @param _header The raw bytes header
/// @param _prevHeaderDigest The previous header's digest
/// @return true if the connect is valid, false otherwise
function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) {
// Extract prevHash of current header
bytes32 _prevHash = _header.extractPrevBlockLE().toBytes32();
// Compare prevHash of current header to previous header's digest
if (_prevHash != _prevHeaderDigest) {return false;}
return true;
}
}
pragma solidity ^0.5.10;
/** @title CheckBitcoinSigs */
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {BTCUtils} from "./BTCUtils.sol";
library CheckBitcoinSigs {
using BytesLib for bytes;
using BTCUtils for bytes;
/// @notice Derives an Ethereum Account address from a pubkey
/// @dev The address is the last 20 bytes of the keccak256 of the address
/// @param _pubkey The public key X & Y. Unprefixed, as a 64-byte array
/// @return The account address
function accountFromPubkey(bytes memory _pubkey) internal pure returns (address) {
require(_pubkey.length == 64, "Pubkey must be 64-byte raw, uncompressed key.");
// keccak hash of uncompressed unprefixed pubkey
bytes32 _digest = keccak256(_pubkey);
return address(uint256(_digest));
}
/// @notice Calculates the p2wpkh output script of a pubkey
/// @dev Compresses keys to 33 bytes as required by Bitcoin
/// @param _pubkey The public key, compressed or uncompressed
/// @return The p2wkph output script
function p2wpkhFromPubkey(bytes memory _pubkey) internal pure returns (bytes memory) {
bytes memory _compressedPubkey;
uint8 _prefix;
if (_pubkey.length == 64) {
_prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;
_compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(0, 32));
} else if (_pubkey.length == 65) {
_prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;
_compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(1, 32));
} else {
_compressedPubkey = _pubkey;
}
require(_compressedPubkey.length == 33, "Witness PKH requires compressed keys");
bytes memory _pubkeyHash = _compressedPubkey.hash160();
return abi.encodePacked(hex"0014", _pubkeyHash);
}
/// @notice checks a signed message's validity under a pubkey
/// @dev does this using ecrecover because Ethereum has no soul
/// @param _pubkey the public key to check (64 bytes)
/// @param _digest the message digest signed
/// @param _v the signature recovery value
/// @param _r the signature r value
/// @param _s the signature s value
/// @return true if signature is valid, else false
function checkSig(
bytes memory _pubkey,
bytes32 _digest,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal pure returns (bool) {
require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey");
address _expected = accountFromPubkey(_pubkey);
address _actual = ecrecover(_digest, _v, _r, _s);
return _actual == _expected;
}
/// @notice checks a signed message against a bitcoin p2wpkh output script
/// @dev does this my verifying the p2wpkh matches an ethereum account
/// @param _p2wpkhOutputScript the bitcoin output script
/// @param _pubkey the uncompressed, unprefixed public key to check
/// @param _digest the message digest signed
/// @param _v the signature recovery value
/// @param _r the signature r value
/// @param _s the signature s value
/// @return true if signature is valid, else false
function checkBitcoinSig(
bytes memory _p2wpkhOutputScript,
bytes memory _pubkey,
bytes32 _digest,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal pure returns (bool) {
require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey");
bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer?
if (!_isExpectedSigner) {return false;}
bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s);
return _sigResult;
}
/// @notice checks if a message is the sha256 preimage of a digest
/// @dev this is NOT the hash256! this step is necessary for ECDSA security!
/// @param _digest the digest
/// @param _candidate the purported preimage
/// @return true if the preimage matches the digest, else false
function isSha256Preimage(
bytes memory _candidate,
bytes32 _digest
) internal pure returns (bool) {
return sha256(_candidate) == _digest;
}
/// @notice checks if a message is the keccak256 preimage of a digest
/// @dev this step is necessary for ECDSA security!
/// @param _digest the digest
/// @param _candidate the purported preimage
/// @return true if the preimage matches the digest, else false
function isKeccak256Preimage(
bytes memory _candidate,
bytes32 _digest
) internal pure returns (bool) {
return keccak256(_candidate) == _digest;
}
/// @notice calculates the signature hash of a Bitcoin transaction with the provided details
/// @dev documented in bip143. many values are hardcoded here
/// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)
/// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))
/// @param _inputValue the value of the input in satoshi
/// @param _outputValue the value of the output in satoshi
/// @param _outputScript the length-prefixed output script
/// @return the double-sha256 (hash256) signature hash as defined by bip143
function wpkhSpendSighash(
bytes memory _outpoint, // 36-byte UTXO id
bytes20 _inputPKH, // 20-byte hash160
bytes8 _inputValue, // 8-byte LE
bytes8 _outputValue, // 8-byte LE
bytes memory _outputScript // lenght-prefixed output script
) internal pure returns (bytes32) {
// Fixes elements to easily make a 1-in 1-out sighash digest
// Does not support timelocks
bytes memory _scriptCode = abi.encodePacked(
hex"1976a914", // length, dup, hash160, pkh_length
_inputPKH,
hex"88ac"); // equal, checksig
bytes32 _hashOutputs = abi.encodePacked(
_outputValue, // 8-byte LE
_outputScript).hash256();
bytes memory _sighashPreimage = abi.encodePacked(
hex"01000000", // version
_outpoint.hash256(), // hashPrevouts
hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000)
_outpoint, // outpoint
_scriptCode, // p2wpkh script code
_inputValue, // value of the input in 8-byte LE
hex"00000000", // input nSequence
_hashOutputs, // hash of the single output
hex"00000000", // nLockTime
hex"01000000" // SIGHASH_ALL
);
return _sighashPreimage.hash256();
}
/// @notice calculates the signature hash of a Bitcoin transaction with the provided details
/// @dev documented in bip143. many values are hardcoded here
/// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)
/// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))
/// @param _inputValue the value of the input in satoshi
/// @param _outputValue the value of the output in satoshi
/// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))
/// @return the double-sha256 (hash256) signature hash as defined by bip143
function wpkhToWpkhSighash(
bytes memory _outpoint, // 36-byte UTXO id
bytes20 _inputPKH, // 20-byte hash160
bytes8 _inputValue, // 8-byte LE
bytes8 _outputValue, // 8-byte LE
bytes20 _outputPKH // 20-byte hash160
) internal pure returns (bytes32) {
return wpkhSpendSighash(
_outpoint,
_inputPKH,
_inputValue,
_outputValue,
abi.encodePacked(
hex"160014", // wpkh tag
_outputPKH)
);
}
/// @notice Preserved for API compatibility with older version
/// @dev documented in bip143. many values are hardcoded here
/// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)
/// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))
/// @param _inputValue the value of the input in satoshi
/// @param _outputValue the value of the output in satoshi
/// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))
/// @return the double-sha256 (hash256) signature hash as defined by bip143
function oneInputOneOutputSighash(
bytes memory _outpoint, // 36-byte UTXO id
bytes20 _inputPKH, // 20-byte hash160
bytes8 _inputValue, // 8-byte LE
bytes8 _outputValue, // 8-byte LE
bytes20 _outputPKH // 20-byte hash160
) internal pure returns (bytes32) {
return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 `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));
}
}
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.
*
* > 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.5.0;
import "./IERC20.sol";
/**
* @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;
}
}
pragma solidity ^0.5.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
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);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either `approve` or `setApproveForAll`.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either `approve` or `setApproveForAll`.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
pragma solidity ^0.5.0;
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "../../introspection/ERC165.sol";
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
pragma solidity ^0.5.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../drafts/Counters.sol";
import "../../introspection/ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
pragma solidity ^0.5.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
pragma solidity ^0.5.0;
/**
* @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;
}
}
pragma solidity ^0.5.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* [EIP](https://eips.ethereum.org/EIPS/eip-165).
*
* 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
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.5.0;
import "./IERC165.sol";
/**
* @dev Implementation of the `IERC165` interface.
*
* Contracts may inherit from this and call `_registerInterface` to declare
* their support of an interface.
*/
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) external view 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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity ^0.5.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
| @notice Notifies the contract that the courtesy period has elapsed. @dev This is treated as an abort, rather than fraud. @param _d Deposit storage pointer. | function notifyCourtesyCallExpired(DepositUtils.Deposit storage _d) external {
require(_d.inCourtesyCall(), "Not in a courtesy call period");
require(block.timestamp >= _d.courtesyCallInitiated.add(TBTCConstants.getCourtesyCallTimeout()), "Courtesy period has not elapsed");
startLiquidation(_d, false);
}
| 7,283,196 | [
1,
1248,
5032,
326,
6835,
716,
326,
21833,
1078,
93,
3879,
711,
9613,
18,
540,
1220,
353,
13974,
487,
392,
6263,
16,
9178,
2353,
284,
354,
1100,
18,
282,
389,
72,
225,
4019,
538,
305,
2502,
4407,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
5066,
29328,
1078,
93,
1477,
10556,
12,
758,
1724,
1989,
18,
758,
1724,
2502,
389,
72,
13,
3903,
288,
203,
3639,
2583,
24899,
72,
18,
267,
29328,
1078,
93,
1477,
9334,
315,
1248,
316,
279,
21833,
1078,
93,
745,
3879,
8863,
203,
3639,
2583,
12,
2629,
18,
5508,
1545,
389,
72,
18,
71,
477,
1078,
93,
1477,
2570,
10206,
18,
1289,
12,
25730,
15988,
2918,
18,
588,
29328,
1078,
93,
1477,
2694,
1435,
3631,
315,
29328,
1078,
93,
3879,
711,
486,
9613,
8863,
203,
3639,
787,
48,
18988,
350,
367,
24899,
72,
16,
629,
1769,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.